Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of _ _ init__ and _ _ new__ methods in Python

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about the usefulness of the _ _ init__ and _ _ new__ methods in Python. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

_ _ init _ _ method

The init method is responsible for initializing the object. The object already exists before the system executes the method, otherwise what else is initialized? Let's look at the example first:

# class A (object): python2 must explicitly inherit objectclass A: def _ _ init__ (self): print ("_ init__") super (A, self). _ _ init__ () def _ new__ (cls): print ("_ new__") return super (A) Cls). _ new__ (cls) def _ _ call__ (self): # you can define any parameter print ('_ call__') A ()

Output

_ _ new____init__

The editor recommends a study of python, qun 740, 3222 and 34.

Whether you are Daniel or Xiaobai, whether you want to change careers or want to join the profession, you can learn about making progress and learning together! There are development tools in the skirt, a lot of practical information and technical information to share!

Judging from the output, the new method is called first, returning an instance object, and then init is called. The call method is not called. Let's talk about this at the end. Let's talk about the first two methods, which are slightly rewritten as:

Def _ _ init__ (self): print ("_ init__") print (self) super (A, self). _ init__ () def _ new__ (cls): print ("_ new__") self = super (A, cls). _ _ new__ (cls) print (self) return self

Output:

_ _ new__ init__

From the output, the return value of the new method is the instance object of the class, which is passed to the self parameter defined in the init method so that the instance object can be initialized correctly.

If the new method does not return a value (or None), then init will not be called, which makes sense, because the instance objects have not been created, and there is no point in calling init. In addition, Python also stipulates that init can only return a value of None, otherwise an error will be reported, which will be left to everyone to try.

The _ _ init _ _ method can be used to do some initialization work, such as initializing the state of the instance object:

Def _ init__ (self, a, b): self.a = a self.b = b super (A, self). _ _ init__ ()

In addition, the parameters defined in the _ _ init _ _ method except for self will be consistent or equivalent with the parameters in the new method except for the cls parameter.

Class B: def _ init__ (self, * args, * * kwargs): print ("init", args, kwargs) def _ new__ (cls, * args, * * kwargs): print ("new", args, kwargs) return super (). _ new__ (cls) B (1,2,3) # output new (1,2,3) {} init (1,2,3) {}

_ _ new _ _ method

Normally we don't override this method unless you know exactly what to do and when you care about it. It is used as a constructor to create an object, a factory function dedicated to production instance objects. One of the famous design patterns, the singleton pattern, can be implemented in this way. You may use it when you write your own framework-level code, and we can also find its application scenarios in the open source code, such as the mini Web framework Bootle.

Class BaseController (object): _ singleton = None def _ _ new__ (cls, * a, * k): if not cls._singleton: cls._singleton = object.__new__ (cls, * a, * * k) return cls._singleton

This code is from https://github.com/bottlepy/bottle/blob/release-0.6/bottle.py.

This is one way to implement the singleton pattern through the new method. If the instance object exists, it can be returned directly. If not, create an instance first and then return it. Of course, there is more than one way to implement the singleton pattern, as the Python Zen says:

There should be one-- and preferably only one-- obvious way to do it.

In one way, it's best to have only one way to do one thing.

Thank you for reading! This is the end of this article on "what is the use of _ _ init__ and _ _ new__ methods in Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report