Singleton in python
If you wish to have a singleton class, you can achive it by implementing a decorator:
def singleton(*args, **kwargs):
def initalizer(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance()
return initalizer
Now you can use it like this:
@singleton(10)
class MyClass:
def __init__(self, something):
self.inner = something
def me(self):
print self.inner
All the arguments provided in the sigleton decorator will be used to initalize a class. And you can use it like this
MyClass.me()
Written by Dominik "Socek" Długajczyk
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#