【发布时间】:2017-12-31 18:21:55
【问题描述】:
为什么会这样:
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)
虽然是循环引用:
import sys
print(sys.getrefcount(b))
# ref count is 3 when normally it is 2
但不是这个:
class Bunch(dict):
@property
def __dict__(self):
return self
b = Bunch()
b["a"] = 1
b.a
# raises AttributeError
虽然__dict__ 是大多数外观的属性,但在幕后实现了一些特殊行为,绕过了property 创建的描述符逻辑。
【问题讨论】:
-
想想
self.__dict__ = self。显然,这不能等同于self.__dict__['__dict__'] = self,对吧?所以self.__dict__一定很神奇。 -
@OferSadan:不,函数与否无关紧要,反正在第二个例子中它不是一个函数。