下面是从Python2.7.12文档中检索到的代码片段(3.4.12)。新样式类的特殊方法查找¶):
In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the
__getattribute__()
method even of the object’s metaclass:>>> class Meta(type): ... def __getattribute__(*args): ... print "Metaclass getattribute invoked" ... return type.__getattribute__(*args) ... >>> class C(object): ... __metaclass__ = Meta ... def __len__(self): ... return 10 ... def __getattribute__(*args): ... print "Class getattribute invoked" ... return object.__getattribute__(*args) ... >>> c = C() >>> c.__len__() # Explicit lookup via instance Class getattribute invoked 10 >>> type(c).__len__(c) # Explicit lookup via type Metaclass getattribute invoked 10 >>> len(c) # Implicit lookup 10
我的问题是,为什么在执行type(c).__len__(c)
时调用元类__getattribute__
?在
由于type(c)
生成{C.__len__(c)
。C.__len__
是一个在类C
中定义的未绑定方法,它可以在C.__dict__
中找到,那么为什么{
引用同一文件3.4.2.1。新样式类的更多属性访问:
类
C
是元类Meta
的一个实例,因此当C.__len__
被访问时,Meta.__getattribute__
被调用,即使后者可以在C.__dict__
中找到。在事实上,访问}仍然会被调用。在
C.__dict__
也是一种属性访问,因此{相关问题 更多 >
编程相关推荐