Why is this Python Borg / Singleton pattern working

折月煮酒 提交于 2019-12-09 07:55:12

问题


i just stumbled around the net and found these interesting code snipped:

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!

I understand what a singleton is but i don't understand that particular code snipped. Could you explain me how/where "__shared_state" is even changed at all?

I tried it in 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]: 

but cannot fully understand how this could happen.


回答1:


Because the class's instance's __dict__ is set equal to the __share_state dict. They point to the same object. (Classname.__dict__ holds all of the class attributes)

When you do:

b1.foo = "123"

You're modifying the dict that both b1.__dict__ and Borg.__shared_state refer to.




回答2:


The __init__ method, which is called after instantiating any object, replaces the __dict__ attribute of the newly created object with the class attribute __shared_state.

a.__dict__, b.__dict__ and Borg._Borg__shared_state are all the same object. Note that we have to add the implicit prefix _Borg when accessing private attribute from outside the class.

In [89]: a.__dict__ is b.__dict__ is Borg._Borg__shared_state
Out[89]: True



回答3:


The instances are separate objects, but by setting their __dict__ attributes to the same value, the instances have the same attribute dictionary. Python uses the attribute dictionary to store all attributes on an object, so in effect the two instances will behave the same way because every change to their attributes is made to the shared attribute dictionary.

However, the objects will still compare unequal if using is to test equality (shallow equality), since they are still distinct instances (much like individual Borg drones, which share their thoughts but are physically distinct).



来源:https://stackoverflow.com/questions/12127925/why-is-this-python-borg-singleton-pattern-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!