为什么类 __dict__ 是映射代理? [英] Why is a class __dict__ a mappingproxy?
问题描述
我想知道为什么一个类 __dict__
是一个 mappingproxy
,而一个实例 __dict__
只是一个普通的 dict
这有助于解释器确保类级属性和方法的键只能是字符串.
在其他地方,Python 是一种成人同意的语言",这意味着对象的 dicts 是公开的并且可由用户更改.但是,对于类的类级别属性和方法的情况,如果我们能够保证键是字符串,我们就可以简化和加快类级别属性和方法查找的常见案例代码.特别是,新式类的 __mro__ 搜索逻辑通过假设类 dict 键是字符串来简化和加速.
I wonder why a class __dict__
is a mappingproxy
, but an instance __dict__
is just a plain dict
>>> class A:
... pass
>>> a = A()
>>> type(a.__dict__)
<class 'dict'>
>>> type(A.__dict__)
<class 'mappingproxy'>
This helps the interpreter assure that the keys for class-level attributes and methods can only be strings.
Elsewhere, Python is a "consenting adults language", meaning that dicts for objects are exposed and mutable by the user. However, in the case of class-level attributes and methods for classes, if we can guarantee that the keys are strings, we can simplify and speed-up the common case code for attribute and method lookup at the class-level. In particular, the __mro__ search logic for new-style classes is simplified and sped-up by assuming the class dict keys are strings.
这篇关于为什么类 __dict__ 是映射代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!