Here I have implemented the Singleton base class using __new__. I was reading thru Bruce Eckel's http://www.mindview.net/Books/TIPython and thought OnlyOne can be more simple....
Are there any differences in between two approaches?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class OnlyOne(object):
"""
Signleton class , only one obejct of this type can be created
any class derived from it will be Singleton
"""
__instance = None
def __new__(typ, *args, **kwargs):
if OnlyOne.__instance == None:
obj = object.__new__(typ, *args, **kwargs)
OnlyOne.__instance = obj
return OnlyOne.__instance
print OnlyOne() == OnlyOne()
# testing derived class
class My1(OnlyOne): pass
print My1() == My1()
|
Tags: oop
other singleton (and related) recipes. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465850 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/412551
There are many more. Just search for 'singleton'.
Is this just noise? The solution is okay, but I've seen hundreds of these, and some exactly the same. This entry looks like noise in an attempt to ... ... maybe create presence ? Is the submitter planning a patent application. He won't be the first.
looks like we need to make this three lines atomic...
My porpose in neither to generate noise nor presence... i just wanted to know how is the solution and which one i use if i need signleton?