Singletonize any class

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
pythopian pythopian is offline Offline Nov 11th, 2009, 4:59 pm |
2
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.
Quick reply to this message  
Python Syntax
  1. def Singleton(cls):
  2. instance = []
  3. def create(*args, **kw):
  4. if not instance:
  5. instance.append(cls(*args, **kw))
  6. return instance[0]
  7. return create
  8.  
  9. # Test:
  10.  
  11. TheList = Singleton(list)
  12.  
  13. def test2():
  14. mylist1 = TheList([1,2,3])
  15. mylist2 = TheList()
  16. print mylist1, mylist2
  17. mylist1.append(4)
  18. del mylist1[1]
  19. print mylist1, mylist2
  20.  
  21. >>> test2()
  22. [1, 2, 3] [1, 2, 3]
  23. [1, 3, 4] [1, 3, 4]

Tags
singleton

Message:


Similar Threads
Thread Tools Search this Thread



Tag cloud for singleton
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC