Construction (__new__) and initialization (__init__)

Through the content of the previous article, we already know that when defining a class, we often use the __init__(self) method to set attributes when instantiating the object. For example, the following example:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class User(object):
    def __init__(self, name, age):
        self.name = name;
        self.age = age;
user=User('两点水',23)

In fact, the process of creating a class is divided into two steps, one is to create the object of the class, and the other is to initialize the class. __new__ is used to create a class and return an instance of this class, while __init__ just initializes the instance with the passed parameters. __new__ will definitely be called during the process of creating an instance, but __init__ will not necessarily be called, such as through pickle When deserializing an instance using .load, the __init__ method will not be called.

0c41739cbc728401d6b87605a65a7e9.png

def __new__(cls) is called before the def __init__(self) method, and its function is to return an instance object. Another thing to note is that the __new__ method always needs to return an instance of the class, and __init__ cannot return any value except None

Specific example:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class User(object):
    def __new__(cls, *args, **kwargs):
        # 打印 __new__方法中的相关信息
        print('调用了 def __new__ 方法')
        print(args)
        # 最后返回父类的方法
        return super(User, cls).__new__(cls)
    def __init__(self, name, age):
        print('调用了 def __init__ 方法')
        self.name = name
        self.age = age
if __name__ == '__main__':
    usr = User('两点水', 23)

Look at the output The result:

调用了 def __new__ 方法
('两点水', 23)
调用了 def __init__ 方法

Judging from the printed results, we can know what the process of creating a class is like. First, the __new__ method is called to create an object, and the parameters are passed to the __init__ method. Instantiate.

In fact, in actual development, the __new__ method is rarely used unless you want to be able to control the creation of a class. Usually when talking about __new__, it all involves metaclass.

Of course when the life cycle of an object ends, the destructor __del__ method will be called. But this method is used by Python itself to garbage collect objects.


Continuing Learning
||
submitReset Code