#singleton patterns, such as database objects, are instantiated with the same parameters, and there is no need to duplicate objects, wasting memoryclassMysql:__instance=Nonedef __init__(self,host='127.0.0.1', port='3306'): Self.host=host Self.port=Port @classmethoddefSingleton (cls,*args,**Kwargs):if notCls.__instance: CLS.__instance=cls (*args,**Kwargs)returnCls.__instanceobj1=Mysql () obj2=Mysql ()Print(obj1 isOBJ2)#Falseobj3=Mysql.singleton () Obj4=Mysql.singleton ()Print(obj3 isOBJ4)#True
#application: Custom meta-class for single-instance modeclassMymeta (type):def __init__(self,name,bases,dic):#triggers when class mysql is definedSelf.__instance=None Super ().__init__(name,bases,dic)def __call__(Self, *args, **kwargs):#Mysql (...) Trigger when if notSelf.__instance: Self.__instance=object.__new__(self)#Generating ObjectsSelf.__init__(self.)__instance, *args,**kwargs)#Initializing Objects #The above two steps can be synthesized in the following step #self.__instance=super (). __call__ (*args,**kwargs) returnSelf.__instanceclassMysql (metaclass=Mymeta):def __init__(self,host='127.0.0.1', port='3306'): Self.host=host Self.port=portobj1=Mysql () obj2=Mysql ()Print(obj1 isOBJ2)
Python review-Singleton mode