为什么从类和实例获取属性的查找过程不同? [英] Why are the lookup procedures for getting an attribute from a class and from an instance different?
问题描述
坚果壳中的Python描述了获取属性时的查找过程.这本书区分了两种情况
Python in a Nutshell describes the lookup procedures when getting an attribute. The book distinguishes two cases
-
从类获取属性时的查找过程,例如
cls.name
从课程中获取属性
使用语法C.name
引用属性时
在类对象C
上,查找过程分为两个步骤:
When you use the syntax C.name
to refer to an attribute
on a class object C
, the lookup proceeds in two steps:
-
当
name
是C.__dict__
中的键时,C.name
从C.__dict__['name']
中获取值v
.然后,当v
是 描述符(即type(v)
提供了一个名为__get__
),C.name
的值是调用的结果type(v).__get__(v, None, C)
.如果v
不是描述符,C.name is v
的值.
When
name
is a key inC.__dict__
,C.name
fetches the valuev
fromC.__dict__['name']
. Then, whenv
is a descriptor (i.e.,type(v)
supplies a method named__get__
), the value ofC.name
is the result of callingtype(v).__get__(v, None, C)
. Whenv
is not a descriptor, the value ofC.name is v
.
如果name
不是C.__dict__
中的键,则C.name
将查找委托给C
的基类,这意味着它在C
的基类上循环
祖先类,并在每个方法上尝试名称查找(在方法中
解决方法的顺序,如第方法解决方法的顺序"在页面上所述
113).
When name
is not a key in C.__dict__
, C.name
delegates the lookup to C
’s base classes, meaning it loops on C
’s
ancestor classes and tries the name lookup on each (in method
resolution order, as covered in "Method resolution order" on page
113).
the lookup procedure when getting an attribute from an instance, e.g. obj.name
从这本书开始,自Python 3起,每个类对象实际上都是其元类的实例(例如type
类),为什么从类中获取属性的查找过程以及从中获取属性的查找过程为何呢?实例的其他属性?
Since in Python 3, every class object is actually an instance of its metaclass (e.g. type
class), according to the book, why are the lookup procedure for getting an attribute from a class and the lookup procedure for getting an attribute from an instance different?
推荐答案
它们没有什么不同,本书只是在这里掩盖了元类的概念,因为大多数类都是基本type
的实例,没有特殊行为.如果您有除type
以外的元类,则在类上查找属性时将应用完整的实例查找规则(只是该类的类是元类).
They're not different, the book is just glossing over the concept of metaclasses here, since most classes are instances of the base type
, which has no special behaviors. If you have a metaclass other than type
, the full instance lookup rules apply when looking up attributes on a class (it's just the class of the class is the metaclass).
他们可能只是想尽早避免元类的复杂性.
They were probably either trying to avoid the complexity of metaclasses early on, that's all.
这篇关于为什么从类和实例获取属性的查找过程不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!