##基于classmethod
class Mysql(object): _instance =None def __init__(self,host,port): self.host = host self.port = port @classmethod def singleton(cls): if not cls._instance: cls._instance=cls('127.0.0.1',8000) return cls._instance obj1=Mysql.singleton() obj2=Mysql.singleton() obj3=Mysql('192.168.10.1',3306) print(id(obj1),id(obj2),id(obj3)) #1475724158400 1475724158400 1475724160304
##基于装饰器
def singelton(cls): _instance = cls('127.0.0.1',8000)#先对传入的类实例化一个对象 def inner(*args,**kwargs): if args or kwargs: obj = cls(*args,**kwargs) return obj return _instance return inner @singelton #相当于 Mysql = singelton(Mysql)=inner class Mysql(object): def __init__(self,host,port): self.host = host self.port = port obj1 = Mysql() obj2 = Mysql() obj3=Mysql('192.168.1.1',3306) print(id(obj1),id(obj2),id(obj3))#1744683247040 1744683247040 1744683249112