我只是在网上偶然发现这些有趣的代码被剪掉了:
http://code.activestate.com/recipes/66531/
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
# and whatever else you want in your class -- that's all!
我了解单例是什么,但我不明白特定的代码被剪断了。你能解释一下“__shared_state”是如何/在哪里改变的吗?
我在 ipython 中尝试过:
In [1]: class Borg:
...: __shared_state = {}
...: def __init__(self):
...: self.__dict__ = self.__shared_state
...: # and whatever else you want in your class -- that's all!
...:
In [2]: b1 = Borg()
In [3]: b2 = Borg()
In [4]: b1.foo="123"
In [5]: b2.foo
Out[5]: '123'
In [6]:
但不能完全理解这是怎么发生的。