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.
A mappingproxy is simply a dict with no __setattr__
method.
You can check out and refer to this code.
from types import MappingProxyType
d={'key': "value"}
m = MappingProxyType(d)
print(type(m)) # <class 'mappingproxy'>
m['key']='new' #TypeError: 'mappingproxy' object does not support item assignment
mappingproxy is since Python 3.3. The following code shows dict types:
class C:pass
ci=C()
print(type(C.__dict__)) #<class 'mappingproxy'>
print(type(ci.__dict__)) #<class 'dict'>
来源:https://stackoverflow.com/questions/32720492/why-is-a-class-dict-a-mappingproxy