为什么在这里调用元类getattribute?

2024-05-14 16:30:43 发布

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

下面是从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__中找到,那么为什么{}会参与查找?在


Tags: ofthe方法instancelenreturnobjectdef
1条回答
网友
1楼 · 发布于 2024-05-14 16:30:43

引用同一文件3.4.2.1。新样式类的更多属性访问:

object.__getattribute__(self, name)

Called unconditionally to implement attribute accesses for instances of the class. ...

C是元类Meta的一个实例,因此当C.__len__被访问时,Meta.__getattribute__被调用,即使后者可以在C.__dict__中找到。在

事实上,访问C.__dict__也是一种属性访问,因此{}仍然会被调用。在

相关问题 更多 >

    热门问题