Why is this Python Borg / Singleton pattern working

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

提交回复
热议问题