使用模块
python的模块在第一次导入时会生成.pyc文件,当第二次导入时就会直接加载.pyc文件,而不会再次执行模块代码。
只需将其单独放在一个模块里,并创建一个实例,外部使用时直接调用该实例即可。
使用__new__方法
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is not None: cls._instance = super().__new__(*args, **kwargs) return cls._instance class Myclass(Singleton): a = 1 class1 = Myclass() class2 = Myclass() print(class1 is class2)
使用装饰器
from functools import wraps def singleton(cls): instances = {} @wraps(cls) def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance @singleton class Myclass(): a = 1 class1 = Myclass() class2 = Myclass() print(class1 is class2)
使用元类metaclass
class Singleton(type): instances = {} def __call__(cls, *args, **kwargs): if cls not in cls.instances: cls.instances[cls] = super().__call__(*args, **kwargs) return cls.instances[cls] class Myclass(metaclass=Singleton): a = 1 class1 = Myclass() class2 = Myclass() print(class1 is class2)