Python Singleton mode (3 ways)

Source: Internet
Author: User
Tags wrapper

Way One:

#Single-case mode:#Implementation Purpose: Instantiation multiple times, the resulting instance is the same, is the same object, the same namespace (more space-saving)################################### #方式一: Define a class method within a class #################################ImportSettingsclassMysql:__instance=none#define a variable to receive the instantiated object, making it easy to judge    def __init__(self,ip,port): Self.ip=IP self.port=Port#@classmethod#Make a class method #绑定给Mysql类去直接调用实例化    deffrom_conf (CLS):#The goal is to pick up the MySQL class by reading the IP, port parameters from the configuration file, completing the call to the Init method, and getting an object that instantiates the Init method        #MySQL (settings. Ip,settings. PORT)        #if so, each time the instantiated object is a different namespace, but the data is the same        #return CLS (settings. Ip,settings. PORT) #cls (Ip,port) is called the Init method        #evolution of the final version: Thinking can be unified to define an initial variable __instance=none, the first instance of the object passed to him, every time outside the visit directly        ifCls.__instance  isnone:cls.__instance=CLS (Settings. Ip,settings. PORT)returnAl1.__instance#Previous Versions:#p1=mysql.from_conf ()#print (p1) #<__main__. Mysql object at 0x02be82b0> #数据是同一份, but each time it is instantiated, it points to a different memory address#p2=mysql.from_conf ()#print (p2) #<__main__. Mysql object at 0x02c1ab90>#This is the perfect way to achieve isolation:#after upgrading the version, can be implemented, access to the same things, can point to the same memory spaceobj=mysql.from_conf ()Print(obj.__dict__)#you can also pass in new parameters and create a new namespaceObj2=mysql ('3.3.3.3', 8888)Print(Obj2.__dict__)

Way two:

#Way two: adornersImportSettingsdefSingleton (CLS):__instance=CLS (settings. Ip,settings. PORT)#to the MySQL init method, instantiate an object, __instance    defWrapper (*args,**kwargs):#when judging the outside call, is there a value coming in        ifLen (args) = = 0 andLen (kwargs) = =0:return __instance              #The user does not transmit the parameter, meaning directly returns the value of the default settings        returnCLS (*args,**kwargs)#Otherwise, a new value is created    returnWrapper@singletonclassMysql:##Mysql =singleton (Mysql) #Mysql =wrapper    def __init__(self,ip,port): Self.ip=IP self.port=PortdefAA (self):Print('IP Address:%s Port:%s'%(self.ip,self.port))#The result of the implementation is: to achieve the MySQL does not pass parameters, the default point to the same instance#Call without arguments: guarantees that each instantiation gets the same memory addressObj1=mysql ()#wrapper ()Obj2=mysql ()#wrapper ()Print(Obj1.__dict__, id (obj))#{' IP ': ' 1.1.1.1 ', ' Port ': 3306} 45554896Print(Obj2.__dict__, id (obj))#{' IP ': ' 1.1.1.1 ', ' Port ': 3306} 45554896#In case of a pass, create a newObj2=mysql ('2.2.2.2', 666)Print(Obj2.__dict__)

Way three:

method Three: Custom meta-class#The custom meta class controls the invocation of the class, which is the instantiation of the class: __call__ImportSettingsclassMymeta (type):def __init__(Self,class_name,class_bases,class_dic): Super (mymeta,self).__init__(class_name,class_bases,class_dic)#obj=self.__new__ (self) #造出一个mysql的对象meta        ## self.__init__ (obj,settings. Ip,settings. PORT) #w从配置文件中加载配置完成mysql对象的初始化        ## Self.__instance=obj #拿到一个默认对象, save to a class propertySelf .__instance=self.__new__(self)#Create an empty object first __instanceSelf.__init__(self.)__instance, Settings. Ip,settings. PORT)#Initializes a unique property for an empty object        Print(self.)__instance.__dict__)    def __call__(Self, *args, **kwargs):#in the invoke phase and will trigger the        ifLen (args) ==0 andLen (kwargs) = =0:returnSelf.__instance    ##如果没有会直接传入Obj=self.__new__(self) self.__init__(obj,*args,**Kwargs)returnobjclassMysql (object,metaclass=Mymeta):def __init__(self,ip,port): Self.ip=IP self.port=Port#I got the same memory space address.obj=Mysql () obj1=Mysql () obj2=Mysql ()Print(obj)Print(OBJ1)Print(OBJ2)#get a separate memory address.Obj2=mysql ('3.3.3.3', 8888)Print(Obj2.__dict__)

Python Singleton mode (3 ways)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.