比兹利4e P.E.R第135136页:c英寸副mro?

2024-09-27 21:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

IClass的最后一行到底是做什么的??你知道吗

子检查重载子检查,但通常在 重载运算符我们执行以下操作:

adt + 4.0 here, adt is the user defined type = user class object(instance) and 4.0 is a builtin type which has say .real, .imaginary pre-configured so if adt is complex then this becomes: adt.(self, other) add(self, other) so a reference to 'adt' is generated and fed to 'self' and 'other' refers to 4.0

但在下面的例子中:

class IClass(object):
    def __init__(self):
        self.implementors = set()
    def register(self,C):
        self.implementors.add(C)
    def __instancecheck__(self,x):
        return self.__subclasscheck__(type(x))
    def __subclasscheck__(self,sub):
        return any(c in self.implementors for c in sub.mro())

# Now, use the above object
IFoo = IClass()
IFoo.register(Foo)
IFoo.register(FooProxy)

f = Foo()           # Create a Foo
g = FooProxy(f)     # Create a FooProxy
isinstance(f, IFoo)        # Returns True
isinstance(g, IFoo)        # Returns True
issubclass(FooProxy, IFoo) # Returns True

在这里,self和sub是什么意思??怎么样 子检查过载??你知道吗

不管怎样,假设它不知怎么超载了。。FooProxy的引用是 传递给self和IFoo->;sub.So。。IFoo.mro公司()将生成方法 解析顺序,例如IFoo和IClass。。哪一个 只是个目标。。嗯。。什么??你知道吗

有人能解释一下这是怎么回事吗??基本上“任何”都应该返回 如果FooProxy是IClass中分组类的子类,则为True。你知道吗


Tags: andtoselfregistertrueobjectisdef
1条回答
网友
1楼 · 发布于 2024-09-27 21:23:14

__subclasscheck__是重写内置issubclass的方法。 调用issubclass(X,Y)首先检查Y.__subclasscheck__是否存在,如果存在,则调用Y.__subclasscheck__(X),而不是它的正常实现。

类似地,__instancecheck__是重写内置isinstance的方法。调用isinstance(X, Y)首先检查 Y.__instancecheck__存在,如果存在,则调用Y.__instancecheck__(X) 而不是它的正常实现。

In [121]: class FooProxy3(object):
     ...:     pass

In [122]: issubclass(FooProxy3,IFoo)
Out[122]: False

In [123]: for c in IFoo.implementors:
     ...:     print c
     ...:     
<class '__main__.Foo'>
<class '__main__.FooProxy'>

In [124]: for c in FooProxy3.mro():
     ...:     print c
     ...:     
<class '__main__.FooProxy3'>
<type 'object'>

In [125]: IFoo.register(FooProxy3)

In [126]: for c in IFoo.implementors:
     ...:     print c
     ...:     
<class '__main__.Foo'>
<class '__main__.FooProxy'>
<class '__main__.FooProxy3'>

In [127]: issubclass(FooProxy3,IFoo)
Out[127]: True

让我们考虑上面的例子;创建新类FooProxy3;并检查issubclass;它将返回False(根据Out[122]),因为我们在IFoo.implementors中寻找子类check;而它不存在(根据In[123]
但是当我们有registerFooProxy(这里的意思是;现在我们可以看到它IFoo.implementors);我们可以在IFoo.implementors中看到它Foxproxy3(按照In[126]) 所以当我们检查issubclass;它将返回True
了解更多信息;
Customizing instance and subclass checks
Overloading isinstance() and issubclass()

相关问题 更多 >

    热门问题