为什么类__dict__是mappingproxy?

时间:2021-08-07 10:13:57

I wonder why a class __dict__ is a mappingproxy, but an instance __dict__ is just a plain dict

我想知道为什么一个类__dict__是一个mappingproxy,但一个实例__dict__只是一个简单的字典

>>> class A:
    pass

>>> a = A()
>>> type(a.__dict__)
<class 'dict'>
>>> type(A.__dict__)
<class 'mappingproxy'>

1 个解决方案

#1


45  

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.

在其他地方,Python是一种“同意成人语言”,这意味着用户可以公开和改变对象的序列。但是,对于类的类级属性和方法,如果我们可以保证键是字符串,我们可以简化和加速类级别的属性和方法查找的常见案例代码。特别是,通过假设类dict键是字符串,简化了新样式类的__mro__搜索逻辑并加快了速度。

#1


45  

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.

在其他地方,Python是一种“同意成人语言”,这意味着用户可以公开和改变对象的序列。但是,对于类的类级属性和方法,如果我们可以保证键是字符串,我们可以简化和加速类级别的属性和方法查找的常见案例代码。特别是,通过假设类dict键是字符串,简化了新样式类的__mro__搜索逻辑并加快了速度。