Why are the lookup procedures for getting an attribute from a class and from an instance different?

旧巷老猫 提交于 2019-12-20 07:04:50

问题


Python in a Nutshell describes the lookup procedures when getting an attribute. The book distinguishes two cases

  • the lookup procedure when getting an attribute from a class, e.g. cls.name

    Getting an attribute from a class

    When you use the syntax C.name to refer to an attribute on a class object C, the lookup proceeds in two steps:

    1. When name is a key in C.__dict__, C.name fetches the value v from C.__dict__['name'] . Then, when v is a descriptor (i.e., type(v) supplies a method named __get__ ), the value of C.name is the result of calling type(v).__get__(v, None, C) . When v is not a descriptor, the value of C.name is v .

    2. 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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/44938264/why-are-the-lookup-procedures-for-getting-an-attribute-from-a-class-and-from-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!