单例模式实现
class Single():
__instance = None
@classmethod
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__new__(cls)
return cls.__instance
def singleton(cls):
_instance = {}
def inner(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return inner
@singleton
class Single:
def __init__(self,name):
self.name = name
class Parent(type):
def __init__(self,*args,**kwargs):
self.__instance = None
super().__init__(*args,**kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super().__call__(*args,**kwargs)
return self.__instance
class Child(metaclass=Parent):
def __init__(self,name):
self.name = name