, :
def singleton(cls):
"""Decorate a class with @singleton when There Can Be Only One."""
instance = cls()
instance.__call__ = lambda: instance
return instance
:
@singleton
class MySingleton:
def spam(self):
print id(self)
, , MySingleton , - . MySingleton() . :
>>> MySingleton
<__main__.MySingleton instance at 0x7f474b9265a8>
>>> MySingleton()
<__main__.MySingleton instance at 0x7f474b9265a8>
>>> MySingleton() is MySingleton
True
>>> MySingleton.spam()
139944187291048
>>> MySingleton().spam()
139944187291048