What is the best way to implement the singleton pattern in Python? It seems impossible to declare the constructor private or protected as is normally done with the Singleton pattern...
+1
A:
The Singleton Pattern implemented with Python courtesy of ActiveState.
It looks like the trick is to put the class that's supposed to only have one instance inside of another class.
Mark Biek
2008-09-03 20:54:25
That should be http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python (beta.stackoverflow.com is no more)
James Emerton
2010-06-04 23:49:27
+4
A:
you can ovverdie the new method like this
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
if __name__ == '__main__':
s1=Singleton()
s2=Singleton()
if(id(s1)==id(s2)):
print "Same"
else:
print "Different"
jojo
2009-11-27 19:37:43
+1
A:
Have you guys seen this implementation from Wikipedia? Implementing the singleton pattern with a decorator.
def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance
@singleton class MyClass: ...
Wei
2010-05-02 02:47:11