Why is this Python Borg / Singleton pattern working

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

提交回复
热议问题