Guest User

Untitled

a guest
Nov 16th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. class Singleton(type):
  2. _instances = {}
  3.  
  4. def __call__(cls, *args, **kwargs):
  5. if cls not in cls._instances:
  6. cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
  7. return cls._instances[cls]
  8.  
  9. @property
  10. def instance(cls):
  11. return cls()
  12.  
  13.  
  14. # Usage
  15. class Foo(metaclass=Singleton):
  16. def __init__(self):
  17. self.foo = 1
  18.  
  19.  
  20. class Bar(metaclass=Singleton):
  21. def __init__(self):
  22. self.bar = 2
  23.  
  24.  
  25. print(Foo.instance.foo)
  26. print(Bar.instance.bar)
  27.  
  28. Foo.instance.foo += 10
  29. Bar.instance.bar += 20
  30.  
  31. print(Foo.instance.foo)
  32. print(Bar.instance.bar)
  33.  
  34. Foo().foo += 10
  35. Bar().bar += 20
  36.  
  37. print(Foo().foo)
  38. print(Bar().bar)
Add Comment
Please, Sign In to add comment