6
0

singleton.py 596 B

1234567891011121314151617181920212223242526272829
  1. import abc
  2. class Singleton(abc.ABC):
  3. """ source: https://www.python.org/download/releases/2.2/descrintro/#__new__ """
  4. def __new__(cls, *args, **kwds):
  5. it = cls.__dict__.get("__it__")
  6. if it is not None:
  7. return it
  8. cls.__it__ = it = super(Singleton, cls).__new__(cls)
  9. it.init(*args, **kwds)
  10. return it
  11. @abc.abstractmethod
  12. def init(self, *args, **kwds):
  13. pass
  14. if __name__ == '__main__':
  15. class Test(Singleton):
  16. def init(self):
  17. print("Calling init")
  18. print(id(Test()))
  19. print(id(Test()))