根据Python 2.7.12文档,3.4.2.3。调用描述符¶:
The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance,
a.x
has a lookup chain starting witha.__dict__['x']
, thentype(a).__dict__['x']
, and continuing through the base classes oftype(a)
excluding metaclasses.
但是为什么元类被排除在外?
如果您连续调用type(self)
,无论如何self
是,一个实例对象或一个类型对象,你最终会得到 <type 'type'>
。所以我无法理解为什么元类享有这种“特权”。
顺便说一句,我对这句话有点困惑:例如对象,object.__getattribute__
被使用,所以我认为查找链应该是这样的:
-
a.__dict__['x']
-
type(a).__dict__['x']
-
b.__dict__[x]
对于b
在type(a).__mro__
-
type(b).__dict__[x]
对于b
在type(a).__mro__
-
c.__dict__[x]
对于c
在type(b).__mro__
- ......
我说得对吗?
最佳答案
这是因为属性查找搜索 type(a)
(type(a).__mro__
) 的所有基,而不是所有type(a)
的类型(type(type(a))
)。
此外,type(self)
不会连续调用,因此查找链如下所示:
a.__dict__['x']
type(a).__dict__['x']
b.__dict__[x] for b in type(a).__mro__
引发 AttributeError
正如 @jsbueno 在评论中明智地指出的那样,第二步实际上包含在第三步中。这是因为对于任何类,例如类 C
,C
本身正是 C.__mro__
中的第一项。
关于python - 为什么在实例属性查找中不搜索元类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617090/