Why is this Python Borg / Singleton pattern working

后端 未结 3 2004
鱼传尺愫
鱼传尺愫 2021-02-11 02:14

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

http://code.activestate.com/recipes/66531/

class Borg:
    __shared_state = {}
          


        
相关标签:
3条回答
  • 2021-02-11 02:40

    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).

    0 讨论(0)
  • 2021-02-11 02:41

    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.

    0 讨论(0)
  • 2021-02-11 02:43

    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
    
    0 讨论(0)
提交回复
热议问题