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

How to use the _ _ init__, _ _ new__, _ _ call__ methods of python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "how to use the _ _ init__, _ _ new__, _ _ call__ methods of python". In the daily operation, it is believed that many people have doubts about how to use the _ _ init__, _ _ new__, _ _ call__ methods of python. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful to answer the doubts about how to use the _ _ init__, _ _ new__, _ _ call__ methods of python! Next, please follow the editor to study!

Everything has a process from creation, use, and then to demise. In the object-oriented programming model of programming language, objects have a similar fate: creation, initialization, use, garbage collection. Different stages are executed by different methods (roles).

When defining a class, the _ _ init__ method is most commonly used, while _ _ new__ and _ _ call__ are rarely used. This article attempts to help you explain the correct use and application scenarios of these three methods.

About Python new class and old class in this article do not discuss too much, because the old class is the concept of Python2, now almost no one will use the old class, the new class must explicitly inherit object, while in Python3, only the new class, inherits object by default, no need to show the specification, the code of this article is based on Python3.

_ _ 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 object

Class 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__

Judging from the output, the _ _ new__ method is called first, returning an instance object, and then _ _ init__ is called. The _ _ call__ method has not been 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__

Judging 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__ () _ 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 a 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.

_ _ call__ method

With regard to the _ _ call__ method, we have to first mention a concept, that is, callable objects (callable). The functions, built-in functions and classes that we usually customize belong to callable objects, but whenever a pair of parentheses () can be applied to an object, it can be called a callable object. We can use the function callable to determine whether the object is callable.

If the _ _ call__ method is implemented in the class, then the instance object will also become a callable object, so let's go back to the original example:

A = A () print (callable (a)) # True

An is both an instance object and a callable object, so I can call it like a function. Try it:

A () # _ _ call__

Miraculously, instance objects can also be used as callable objects like functions, so in what scenarios can this feature be used? To combine the characteristics of the class, the class can record data (attributes), but the function is not (closures are also feasible in a sense). Using this feature, you can implement a class-based decorator to record the state in the class, for example, the following example is used to record the number of times a function is called:

Class Counter: def _ init__ (self, func): self.func = func self.count = 0 def _ call__ (self, * args, * * kwargs): self.count + = 1 return self.func (* args, * * kwargs) @ Counterdef foo (): passfor i in range (10): foo () print (foo.count) # 10

There are also use cases of the call method in Bottle. In addition, stackoverflow also has some practical examples about call. It is recommended to take a look, if your project needs to be more abstract, framework code, then these advanced features often play its role.

At this point, the study on "how to use the _ _ init__, _ _ new__, _ _ call__ methods of python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report