为什么从类和实例获取属性的查找过程不同? [英] Why are the lookup procedures for getting an attribute from a class and from an instance different?

查看:60
本文介绍了为什么从类和实例获取属性的查找过程不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

坚果壳中的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:

  1. nameC.__dict__中的键时,C.nameC.__dict__['name']中获取值v.然后,当v是 描述符(即type(v)提供了一个名为 __get__),C.name的值是调用的结果 type(v).__get__(v, None, C).如果v不是描述符, C.name is v的值.

  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 .

如果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).

  • 从实例获取属性时的查找过程,例如obj.name

  • 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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆