Why is this Python Borg / Singleton pattern working

后端 未结 3 2011
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题