In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "what is the use of _ _ new__ method in Python", the content is simple and clear, and I hope it can help you solve your doubts. Let me lead you to study and learn this article "what is the use of _ _ new__ method in Python".
1. Brief introduction of _ _ new__ method
The next step is to explain in detail the existence of the _ _ new _ _ method in the class initialization process through an example.
1. Initialize data loading + parsing class instance class Solution (object): def _ init__ (self, name=None,data=None): self.name = name self.data = data # initializing loading data self.xml_load (self.data) def xml_load (self,data): print ("initializing init", data) def Parser (self): print ("parsing completed finish" Self.name) a = Solution (name= "A111", data=10) a.Parser () b = Solution (name= "A112", data=20) b.Parser () # print (a) and print (b) return the name of the class and the address of the object print (a) print (b) # you can use the built-in function id () to view the memory address of the python object print (id (a) print (id (b)) initialize init 10 to complete finish A111 initialization init 20 parsing to complete finish A112251783980982517841042504
Note:
1. Code instantiation class process
Generally, the _ _ init__ () method is used to initialize an instance of a class. When a class is instantiated in the code, the first call executes the _ _ new__ () method. When there is no redefinition of the _ _ new__ () method in the defined class, Python calls the _ _ new__ () method of the parent class by default to construct the instance. The new method creates a space first. Then create an instantiated object one at a time, and then use the open space to store the instantiated object When you create an instantiated object again, use the new method to open up a space to hold the instantiated object. Note that only classes that inherit object have this method.
2. Memory addresses and objects can be converted into each other
# use the api of _ ctypes to import _ ctypesobj = _ ctypes.PyObj_FromPtr (id (a)) # print out the object print (obj) found by the memory address
Both print (id (a)) and print (id (b)) print out memory addresses (in decimal), while print (a) and print (b) return the name of the class and the address of the object, but they are not the same. Each instantiation class creates a different object address assignment, so the address reference that returns the class object during the code instantiation class is also different.
2, initialize data load rewrite new method + parse class instance class Solution: "Note: the new method is the method to create space for the instantiated object, now the new method has been rewritten, and the interpreter that does not return the instantiated object reference to python cannot create a space storage for the instantiated object, so running the code will report an error. Also did not complete the initialization operation. "" def _ _ new__ (cls, * args, * * kwargs): print ("object creation space") cls.instance = super (). _ _ new__ (cls) print (cls.instance) # return cls.instance # if no instance object reference is returned The instantiation method will report an error: AttributeError: 'NoneType' object has no attribute' Parser' def _ _ init__ (self,name,data): self.name = name self.data = data self.xml_load (self.data) def xml_load (self,data): print ("initialize init", data) def Parser (self): print ("parsing completed finish", self.data) a = Solution ("A111") 10) a.Parser () print (id (a))
Note:
1. The difference between _ _ init__ () method and _ _ new__ () method
The _ _ new__ () method is used to create an instance, which is called first before the class is instantiated. It is a class method and is a static method. The _ _ init__ () method initializes the instance, which is called after the instance object is created, which is the method of the instance object and is used to set some initial values of the class instance object.
If both the _ _ init__ () method and the _ _ new__ () method appear in the class, the _ _ new__ () method is called first and then the _ _ init__ () method is called. The _ _ new__ () method is the first step in creating an instance. After execution, you need to return an instance of the created class, otherwise an error will be reported and the _ _ init__ () method cannot be executed. Where the _ _ init__ () method will not return any information.
2. Override the _ _ new__ () method
Def _ new__ (cls, * args, * * kwargs): print (cls) # cls represents the class Solution itself cls.instance = super (). _ _ new__ (cls) # object (). _ new__ () print (cls.instance) return cls.instance
Both super () and object.__new__ (cls) are calling the new method of the parent class, and the new method of the parent class must be returned to the function to open up space, so return must be added. The order in which the code is executed is that the new method is executed first, then the init method, and finally the other methods.
2. Singleton model
The original definition of the singleton pattern appears in "Design pattern": "ensure that a class has only one instance and provide a global access point to access it."
Singletons are mainly used when it is necessary to ensure that only one instance can be accessed globally, such as the output of the system log, the task manager of the operating system, and so on.
1. How to implement singleton pattern with new method class Solution: # 1. Record the reference of the first created object Represents the private attribute of the class _ instance = None # static variable stored in the class's namespace def _ _ init__ (self,name,data): self.name = name self.data = data self.xml_load (self.data) def _ new__ (cls, * args, * * kwargs): # 2. To determine whether the property of this class is empty; if the first object has not been created, we should call the method of the parent class and allocate space if cls._instance = = None: # 3 for the first object. Return the object reference saved in the class property to python's interpreter cls._instance = object.__new__ (cls) # 3 return cls._instance # if cls._instance is not None, directly return the instantiated instance object else: return cls._instance # must return the address to the new method Give it storage space def xml_load (self,data): print ("initialize init", self.name,data) def Parser (self): print ("parsing completed finish", self.name) a = Solution ("A11", 10) # Open an object space address for the first time Later, a.Parser () b = Solution ("A12", 20) # b overwrites b.Parser () print (id (a)) print (id (b)) # memory address, and their memory address is the same print (a.name) print (b.name).
Output
Initialize init A11 10
Parsing completed finish A11
Initialize init A12 10
Parsing completed finish A12
2465140199816
2465140199816
A12
A12
Note:
1. The singleton mode always has only one space, which is always reused.
First, define the private property _ instance of a class, which is used to record the reference of the first created object. If cls._instance is None indicating that the class has not been instantiated, instantiate the class and return the instance object.
Through the following data tests, print (obj.name, obj.data) finally printed A12, the first print "A11", the attribute is empty, the implementation of if statement opened up a space to store the attribute; from the second hit has opened up a space, the implementation of else statement, directly return to the "A12" to the original space, cover the previous cover data.
Def task (id,data): obj = Solution ("{0}" .format (id), "{0}" .format (data)) print (obj.name, obj.data) import threadingID= ["A11", "A12", "A13", "A14", "A12"] DATA= [10Magne20] for i in range (5): t = threading.Thread (target=task (ID [I], DATA [I]), args= [I,]) t.start ()
Output
Initialize init A11 10
A11 10
Initialize init A12 20
A12 20
Initialize init A13 30
A13 30
Initialize init A14 40
A14 40
Initialize init A12 20
A12 20
2. Another implementation method of singleton pattern.
Def _ _ new__ (cls,*args,**kwargs): # hasattr queries the target and determines whether there is one. Not 1 returns cls.instance = object.... when the # not condition after the False # if statement is True as a whole When the # not condition after the # if statement is False as a whole, execute the return code if not hasattr (cls, "instance"): # hasattr look up, determine the role of cls.instance = object.__new__ (cls) return cls.instance2, and how to control the class to execute initialization methods only once
The above achieves the reuse of singleton pattern object space, but sometimes we want to load the initialization process only once to avoid frequent requests wasting system resources (such as database connection request data).
Class Solution: # define class variable # record the reference of the first created object, which represents the private attribute of the class _ instance = None # record whether the initialization action init_flag = False def _ _ init__ (self,name,data): self.name = name self.data = data # invokes the class variable using the class name and cannot be accessed directly. If Solution.init_flag: return self.xml_load (self.data) # modify the tag of the class attribute Solution.init_flag = True def _ _ new__ (cls, * args, * * kwargs): # determine whether the attribute of the class is empty For the first object that has not been created, we should call the method of the parent class Allocate space for the first object if cls._instance = = None: # return the object reference saved in the class attribute to python's interpreter cls._instance = object.__new__ (cls) return cls._instance # if cls._instance is not None Directly return the instantiated instance object else: return cls._instance def xml_load (self,data): print ("initialize init", self.name,data) def Parser (self): print ("parsing completed finish", self.name) a = Solution ("A11", 10) # the first instantiation object address A.Parser () b = Solution ("A12", 20) # b overwrites b.Parser () print (id (a)) print (id (b)) print (a.name) print (b.name)
Output
Initialize init A11 10
Parsing completed finish A11
Parsing completed finish A12
2280855720328
2280855720328
A12
A12
Note:
1. The initialization process is loaded only once in singleton mode.
At this point, we add another init_flag attribute to the class space to record whether the initialization operation has been performed to achieve the load initialization process. From the results of the above two instantiation processes, the object reference address remains unchanged, the result is overwritten by the last instantiation data, and the initialization init is printed only once.
2. Attention points for the next resource loading in singleton mode
In singleton mode, the control class initializes only once, which is suitable for the process of loading resources into the cache at one time, and can be implemented in multi-case mode for multi-process applications.
Third, multi-case model
Multiple instance object space reference addresses are completely independent, thus keeping different request resources from being occupied. Classify the same object request as the same instance.
Class Solution: # # definition class instantiation object dictionary That is, different instance objects correspond to different object space address references _ loaded = {} def _ _ init__ (self,name,data): self.name = name self.data = data self.xml_load (self.data) def _ new__ (cls, name) * args): if cls._loaded.get (name) is not None: client = cls._loaded.get (name) print (f "access object {name}") print (client) return client # returns the object reference saved in the class attribute to python's interpreter print (f "is creating an access Ask object {name} ") client = super (). _ _ new__ (cls) # add a spatial object address reference print (client) cls._ loaded [name] = client return client def xml_load (self) for this class instance name Data): print ("initialization init", self.name,data) def Parser (self): print ("parsing completed finish", self.name) if _ _ name__ ='_ _ main__': print ("multiple pattern instances") a = Solution ("A11,10) a.Parser () b = Solution (" A11 ", 10) b.Parser () c = Solution (" A12 ") 20) c.Parser () print (f "{an is b}") print (a.name) print (b.name) print (c.name)
Note:
1. Multi-case patterns always have multiple spaces, and different spaces are completely independent.
We define the class instantiation object dictionary in the class space, that is, establish different instance objects and object space address reference key-value pairs, so as to realize the multi-instance pattern. Through the class dictionary to determine whether the instance object is created, saving the cost of creation.
2. Multi-case pattern testing process
When creating the same instance object name= "A11", the program first searches the instance pool for cls._loaded.get (name), and if it exists, it directly returns the created instance object space. The multi-case pattern perfectly realizes the different instantiated object addresses of different access objects.
3. Implementation of buffering mechanism in multi-case mode.
Further optimize the multi-case schema initialization process, such as initializing the load only once when reading a file or database.
Class Solution: # # definition class instantiation object dictionary That is, different instance objects correspond to different object space address references _ loaded = {} def _ _ new__ (cls, name,data) * args): if cls._loaded.get (name) is not None: client = cls._loaded.get (name) print (f "access object {name}") print (client) return client print (f "creating access object {name}") # reference the object saved in the class attribute The interpreter client returned to python = super (). _ _ new__ (cls) print (client) # adds a spatial object address reference cls._ loaded [name] = client client._init_db (name) for this class instance name Data) return client def _ init_db (self,name,data): self.name = name self.data = data self.xml_load (self.data) def xml_load (self,data): print ("initialize init", self.name,data) def Parser (self): print ("parsing completed finish" Self.name) if _ _ name__ = ='_ main__': print ("multiple pattern instances-cache") a = Solution ("A11,10) a.Parser () b = Solution (" A11,10) b.Parser () c = Solution ("A12,20) c.Parser () print (f" {an is b} ") print (a.name) print (b.name) print (c.name)
Output
Creating access object A11
Initialize init A11 10
Parsing completed finish A11
Access object A11 already exists
Parsing completed finish A11
Creating access object A12
Initialize init A12 20
Parsing completed finish A12
True
A11
A11
A12
Note: in multiple case mode, multiple instantiated objects are initialized only once.
The binding initialization _ init_db () method is executed once after each instance object in the _ _ new__ method is created. Nothing will happen if you encounter the same instance object later, and the created instance object will be returned directly. From the test results, when creating the same instance object name= "A11", the initialization data loading process will be skipped for the second time, and the cache mechanism is well implemented.
The above is all the content of the article "what is the use of the _ _ new__ method in Python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.