| | |
Singletonize any class
This is one simple way to emulate a singleton class on behalf of a normal class. (A singleton class is a class with at most one instance.)
The implementation does not emulate a class 100% (for example it lacks the special attributes lile __dict__ or __bases__), but it should be absolutely sufficient in most common cases.
The implementation does not emulate a class 100% (for example it lacks the special attributes lile __dict__ or __bases__), but it should be absolutely sufficient in most common cases.
def Singleton(cls): instance = [] def create(*args, **kw): if not instance: instance.append(cls(*args, **kw)) return instance[0] return create # Test: TheList = Singleton(list) def test2(): mylist1 = TheList([1,2,3]) mylist2 = TheList() print mylist1, mylist2 mylist1.append(4) del mylist1[1] print mylist1, mylist2 >>> test2() [1, 2, 3] [1, 2, 3] [1, 3, 4] [1, 3, 4]
Similar Threads
- Help with Class (C++)
- Problem when calling class online (ASP.NET)
- Code Snippet: Graph class in wxWidgets (C++)
| Thread Tools | Search this Thread |




