home page » programing language » Briefly describe __init__, __new__, __call__ methods

Briefly describe __init__, __new__, __call__ methods

 
Article Contents

Everything has a process from creation, use to extinction. 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 most commonly used is __init__ Method, and __new__ And __call__ It is seldom used. This article tries to help you explain the correct use methods and application scenarios of the three methods.

This article does not discuss the new and old classes of Python too much, because the old class is a concept in Python 2, and no one will use the old class anymore. The new class must explicitly inherit the object, while in Python 3, only the new class inherits the object by default, without the need to display the specification. The code in this article is based on Python 3.

__Init__ method

__init__ The method is responsible for the initialization of the object. Before the system executes the method, the object already exists. Otherwise, what should be initialized? Let's take an example:

 #Class A (object): python2 must explicitly inherit the 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 ):   #Any parameter can be defined
         print ( '__call__ ' )

 A ()

output

 __new__ __init__

From the output results __new__ The method is called first, returns an instance object, and then __init__ Is called.   __call__ The method has not been called. Let's put it at the end. First, let's talk about the first two methods, which is 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__ 
 < __main__ . A  object  at  0x1007a95f8 >
 __init__ 
 < __main__ . A  object  at  0x1007a95f8 >

From the output results, __new__ The return value of the method is the instance object of the class, which will be passed to __init__ Method so that the instance object can be properly initialized.

If __new__ If the method does not return a value (or returns None), then __init__ It will not be called, which also makes sense, because the instance objects have not been created, and it is meaningless to call init. In addition, Python also stipulates that, __init__ Only the value of None can be returned, otherwise an error will be reported. This is left to everyone to try.

__init__ Methods can be used to do some initialization work, such as initializing the status of instance objects:

 def __init__(self,  a, b): self.a = a self.b = b super(A,  self).__init__()

__New__ method

Generally, we will not rewrite this method unless you know exactly how to do it and when you will care about it. It is used as a constructor to create objects. It is a factory function, which is dedicated to producing instance objects. One of the famous design patterns, the singleton pattern, can be realized through this method. When you write your own framework level code, you may use it. We can also find its application scenarios from the open source code, such as the micro 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 comes from https://github.com/bottlepy/bottle/blob/release-0.6/bottle.py

This is through __new__ Method is a way to implement the singleton pattern. If the instance object exists, you can directly return to the instance. If not, you can create an instance first and then return. Of course, there is more than one way to implement the singleton mode, The Zen of Python says:

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

Do one thing in one way, preferably only in one way

__Call__ method

About __call__ Method, I have to mention one concept first, that is Callable The functions, built-in functions and classes we usually define are callable objects, but we can put a pair of brackets () When applied to an object, it can be called a callable object. To determine whether the object is a callable object, you can use the function callable

If you implement __call__ Method, then the instance object will also become a callable object. Let's return to the original example:

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

a It is an instance object and also a callable object, so I can call it like a function. try:

 a()  # __call__

Miraculously, instance objects can also be used as callable objects like functions. In what scenarios can this feature be used? In combination with the characteristics of the class, the class can record data (attributes), but the function cannot (closures are also feasible in a sense). This feature can be used to implement class based decorators and record the status 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 = zero

     def  __call__ ( self , * args , ** kwargs ): self . count += one
         return  self . func (* args , ** kwargs ) @Counter
 def  foo (): pass

 for  i  in  range ( ten ): foo () print ( foo . count ) # 10

There are also use cases of the call method in the Bottom. In addition, stackoverflow There are also some practical examples of call. It is recommended to have a look. If your project needs more abstract and framework code, these advanced features can often play a role.

Source: https://foofish.net/magic-method.html

Original link: Briefly describe __init__, __new__, __call__ methods , Please indicate the source for reprinting!

fabulous three