python - Making __dict__ A Property -
why work:
class bunch(dict): def __init__(self, *args, **kwargs): super(bunch, self).__init__(*args, **kwargs) self.__dict__ = self b = bunch() b["a"] = 1 print(b.a)
albeit circular reference:
import sys print(sys.getrefcount(b)) # ref count 3 when 2
but not this:
class bunch(dict): @property def __dict__(self): return self b = bunch() b["a"] = 1 b.a # raises attributeerror
while __dict__
attribute outward appearances, there's special behavior being implemented behind scenes bypassing descriptor logic created property
.
the default __dict__
attribute is property. (it's not literally property
, it's implemented through descriptor protocol, property
.)
when set self.__dict__ = self
, goes through __dict__
descriptor's __set__
method , replaces dict used instance attributes.
however, python doesn't use __dict__
descriptor find instance dict when performing attribute operations; uses different internal mechanism. thus, creating own __dict__
descriptor doesn't affect attribute lookup mechanism b.a
in second example.
Comments
Post a Comment