单例的三种实现方式
Posted li1992
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例的三种实现方式相关的知识,希望对你有一定的参考价值。
一:类方法实现单例
class mysql: __instance = None def __init__(self,host,port): self.host = host self.port = port q @classmethod def singleton(cls): if not cls.__instance: cls.__instance = cls(setting.host,setting.port) return cls.__instance obj1 = Mysql.singleton() obj2 = Mysql.singleton() print(obj1) print(obj2)
二:自定制元类方法实现单例
import setting class Mymeta(type): def __init__(self,class_name,base,dic): super().__init__(class_name, base, dic)#初始化一个类(mysql) self.__instance = object.__new__(self)#利用mysql类的基类__new__方法造出一个mysql类的对象 self.__init__(self.__instance,setting.host,setting.port)#调用类的__init__方法实例化出这个对象 def __call__(self, *args, **kwargs): #如果对元类的实例化对象mysql类加括号调用则自动触发,元类的对象类mysql会作为第一个参数自动传入 #相当于mysql.__call__() if args or kwargs: obj = object.__new__(self) self.__init__(obj,*args,**kwargs) return obj return self.__instance class Mysql(metaclass=Mymeta):#定义类mysql(实际就是(调用元类的_init__方法)) def __init__(self,host,port): self.host = host self.port = port obj1 = Mysql()#加括号调用,实例化生成对象(调用类的__init__方法) obj2 = Mysql() print(obj1) print(obj2) obj3 = Mysql("129.0.0.1",8080) obj4 = Mysql("129.0.0.1",8080) print(obj3) print(obj4)
三:自定制元类方法实现单例
def sigleton(cls): __instance = cls(setting.host,setting.port) def wrapper(*args,**kwargs): if args or kwargs: # obj = cls(*args, **kwargs) obj = object.__new__(cls) cls.__init__(obj,*args, **kwargs) return obj return __instance return wrapper @sigleton class Mysql: def __init__(self,host,port): self.host = host self.port = port
附:setting.py
port = 8888 host = "127.0.0.1"
以上是关于单例的三种实现方式的主要内容,如果未能解决你的问题,请参考以下文章