单例模式
单例模式就是在多次实例化后得到的是同一个实例
实现单例的第一种方式:
class Mysql: def __init__(self,ip,port): self.ip = ip self.port = port @classmethod def from_conf(cls): if not hasattr(cls,'_Mysql__instance'): cls.__instance = cls(settings.IP,settings.PORT) return cls.__instance
或者:
class Mysql: __instance = None def __init__(self,ip,port): self.ip = ip self.port = port @classmethod def from_conf(cls): if cls.__instance is None: cls.__instance = cls(settings.IP,settings.PORT) return cls.__instance
实现单例的第二种方式:
def foo(cls): __instance = cls(settings.IP,settings.PORT) def wrapper(*args,**kwargs): if args or kwargs: obj = cls(*args,**kwargs) return obj return __instance return wrapper @foo class Mysql: __instance = None def __init__(self,ip,port): self.ip = ip self.port = port
实现单例的第三种方法:
利用元类,来控制类的实例化的过程,在实例化过程中不传参数的时候都指向同一个实例
class Mymeta(type): def __init__(self,class_name,class_base,class_dic): self.__instance = self(settings.IP,settings.PORT) def __call__(self, *args, **kwargs): if args or kwargs: obj = self.__new__(self) self.__init__(obj,*args,**kwargs) return obj else: return self.__instance class Mysql(metaclass=Mymeta): __instance = None def __init__(self,ip,port): self.ip = ip self.port = port
实现单例的第四种方法:
利用导模块的方法实现单例,因为在模块被导入的时候就产生一次名称空间
# 在文件singleton.py中写一个类并且实例化
class Mysql: def __init__(self,ip,port): self.ip = ip self.port = port instance = Mysql('1.1.1.1',3306) # 在别的文件中 from singleton import instance