Why is this Python Borg / Singleton pattern working
我只是在网上绊了一跤,发现这些有趣的代码被剪掉了:
http://code.activestate.com/recipes/66531/
1 2 3 4 5 | class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # and whatever else you want in your class -- that's all! |
我理解单件是什么,但我不理解被截取的特定代码。你能给我解释一下,"共享"状态是如何/在哪里被改变的吗?
我在ipython尝试过:
1 2 3 4 5 6 7 8 9 10 11 12 | 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]: |
但不能完全理解这是如何发生的。
因为class's实例的
当你这样做的时候:
1 | b1.foo ="123" |
您正在修改
实例是单独的对象,但是通过将它们的
但是,如果使用
在实例化任何对象后调用的
1 2 | In [89]: a.__dict__ is b.__dict__ is Borg._Borg__shared_state Out[89]: True |