python - 为什么在实例属性查找中不搜索元类的属性?

标签 python attributes metaclass python-internals getattribute

根据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 with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses.

但是为什么元类被排除在外?

如果您连续调用type(self) ,无论如何self是,一个实例对象或一个类型对象,你最终会得到 <type 'type'> 。所以我无法理解为什么元类享有这种“特权”。

<小时/>

顺便说一句,我对这句话有点困惑:例如对象,object.__getattribute__被使用,所以我认为查找链应该是这样的:

  • a.__dict__['x']
  • type(a).__dict__['x']
  • b.__dict__[x]对于 btype(a).__mro__
  • type(b).__dict__[x]对于 btype(a).__mro__
  • c.__dict__[x]对于 ctype(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 在评论中明智地指出的那样,第二步实际上包含在第三步中。这是因为对于任何类,例如类 CC 本身正是 C.__mro__ 中的第一项。

关于python - 为什么在实例属性查找中不搜索元类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617090/

相关文章:

python - Tornado 的环境信息

c# - 有没有办法将属性应用于首先执行的方法?

python - 哇 six.with_metaclass() 有用吗?

python - 如何替换字符串的后缀?

python - 如何使用指向自身的指针在 ctypes 中设置结构?

php - 添加新产品时向 magento 下拉列表或多选产品属性添加值

python - 我如何子类化 threading.Event?

django - 在 Form Meta 类中设置初始值

python - 使用python查找不为空的最低值

JavaScript 对象,两个问题