Why are the lookup procedures for getting an attri

2020-05-07 09:31发布

问题:

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.