为什么__dict__类是一个映射代理? [英] Why is a class __dict__ a mappingproxy?
问题描述
我想知道为什么类 __ dict __
是 mappingproxy
,但是是实例 __ dict __
只是普通的 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'>
推荐答案
这有助于解释程序确保class-级别属性和方法只能是字符串。
This helps the interpreter assure that the keys for class-level attributes and methods can only be strings.
在其他地方,Python是一种成人同意语言,这意味着对象的指示由用户公开和可变。但是,对于类的类级属性和方法,如果我们可以保证键是字符串,则可以在类级简化和加快用于属性和方法查找的常见案例代码。尤其是,通过假定类dict键为字符串,可以简化和加快用于新型类的__mro__搜索逻辑。
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屋!