mardi 25 juillet 2017

Understanding Borg Singleton Pattern in Python

I saw this Borg Singleton Pattern code but I couldn't get my head around how new members I add to the singleton object gets appended to the __shared_state = {} dictionary.

Here is the Singleton code

class Borg(object):
    _shared_state = {}

    def __new__(cls,*args,**kwargs):
        obj = super(Borg,cls).__new__(cls,*args,**kwargs)
        obj.__dict__ = cls._shared_state
        return obj

class Child(Borg):
    pass

if __name__ == '__main__':
    borg = Borg()
    another_borg = Borg()

    print borg is another_borg
    child = Child()

    borg.only_one_var = "I'm the only one var"    
    print child.only_one_var

So my question when the object borg.only_one_var is created how does it get appended to _shared_state dictionary

Aucun commentaire:

Enregistrer un commentaire