Skip to content

Instantly share code, notes, and snippets.

@gennad
Created May 28, 2011 18:58
Show Gist options
  • Save gennad/997122 to your computer and use it in GitHub Desktop.
Save gennad/997122 to your computer and use it in GitHub Desktop.
Singletone Python
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
a = MyClass()
a.attr = 12
b = MyClass()
print b.attr
# 12
print a is b
# True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment