fork download
  1. class Singleton (object):
  2. def __new__(cls, *args, **kwds):
  3.  
  4. # Tenta pegar a instância existente:
  5. it = cls.__dict__.get("__it__")
  6.  
  7. # Se exitir, retorne-a:
  8. if it is not None:
  9. return it
  10.  
  11. # Se não, crie uma instância nova:
  12. cls.__it__ = it = object.__new__(cls)
  13.  
  14. # Inicializa a instância:
  15. it.init(*args, **kwds)
  16.  
  17. # Retorna a nova instância:
  18. return it
  19.  
  20. def init(self, *args, **kwds):
  21. print("Objeto inicializado")
  22.  
  23. obj1 = Singleton()
  24. obj1.name = "Foo Bar"
  25.  
  26. obj2 = Singleton()
  27. print(obj2.name)
Success #stdin #stdout 0.01s 28352KB
stdin
Standard input is empty
stdout
Objeto inicializado
Foo Bar