Created
March 2, 2016 04:35
-
-
Save drhanlau/6dc95cd22d44eca10c29 to your computer and use it in GitHub Desktop.
Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
borg = Borg() | |
another_borg = Borg() | |
print borg is another_borg | |
child = Child() | |
borg.only_one = "I am the one" | |
print child.only_one |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Singleton(object): | |
def __new__(cls): | |
if not hasattr(cls, 'instance'): | |
cls.instance = super(Singleton, cls).__new__(cls) | |
return cls.instance | |
singleton = Singleton() | |
another_singleton = Singleton() | |
print singleton is another_singleton | |
singleton.only_one_var = "I'm only one var" | |
print another_singleton.only_one_var |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment