class Singleton(object): def foo(self): print(‘foo...‘) my_singleton = Singleton()
from MySingleton import my_singleton print(id(my_singleton)) # 1079832199688 from MySingleton import my_singleton print(id(my_singleton)) # 1079832199688
class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls) return cls._instance class Person(Singleton): def __init__(self, name): self.name = name if __name__ == ‘__main__‘: p1 = Person(‘a‘) p2 = Person(‘b‘) print(id(p1), id(p2)) # 1007394335600 1007394335600 print(p1 == p2) # True print(p1 is p2) # True
from functools import wraps # Create your tests here. def Singleton(cls): _instance = {} @wraps(cls) def wrap(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return wrap @Singleton class Person(): def __init__(self, name): self.name = name if __name__ == ‘__main__‘: p1 = Person(‘a‘) p2 = Person(‘b‘) print(id(p1), id(p2)) # 240896617272 240896617272 print(p1 == p2) # True print(p1 is p2) # True
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Person(metaclass=Singleton): def __init__(self, name): self.name = name if __name__ == ‘__main__‘: p1 = Person(‘a‘) p2 = Person(‘b‘) print(id(p1), id(p2)) # 190305487616 190305487616 print(p1 == p2) # True print(p1 is p2) # True
# Python2 class MyClass(object): __metaclass__ = Singleton # Python3 class MyClass(metaclass=Singleton): pass
原文:https://www.cnblogs.com/ygbh/p/11558449.html