python 创建带参数的单例类(方法其一)

singleton的最佳方法是使用元类

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]

# Python 2
class MyClass():
    __metaclass__= Singleton

# Python 3
class MyClass(metaclass=Singleton):
    
    def __init__(self,obj)
        self.obj = obj
        

参考:

如何在python中创建带参数的单例类 | 码农家园

你可能感兴趣的:(pyhon,python)