Skip to content

Instantly share code, notes, and snippets.

@drhanlau
Created March 2, 2016 04:35
Show Gist options
  • Save drhanlau/6dc95cd22d44eca10c29 to your computer and use it in GitHub Desktop.
Save drhanlau/6dc95cd22d44eca10c29 to your computer and use it in GitHub Desktop.
Singleton
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
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