Class Constructor
The constructor of the python class is _ init __, which is different from other functions. First, it uses two double underscores (_ init __) to distinguish it from other function names. The format is as follows:
Def _ init _ (self, parameter list ):
Def is the key word for defining the function. __init _ is the name of the constructor, and self is the parameter of the class itself, which is used to distinguish the functions that belong to the class. The final parameter list is optional. Constructor is mainly used to initialize member variables and allocate resources. It is a place where classes run immediately after birth. By running the following example and viewing the running results, you can easily know the running sequence:
class Foo: def __init__(self): print(‘__init__‘) def __del__(self): print(‘__del__‘) def foo(self): print(‘foo‘) test = Foo()test.foo()
The output result of this example is as follows:
_ Init __
Foo
_ Del __
Here we can see that the constructor _ init _ outputs first, followed by the function Foo, and finally the Destructor _ del __. Constructor and destructor are not explicitly called here and are automatically executed.
Class destructor
In python, the form of class destructor is as follows:
Def _ del _ (self, parameter list ):
Def is the key word for defining the function, __del _ is the name of the destructor, and self is the parameter of the class itself, similar to the this pointer in C ++, in the class, you can use self to modify the member variables and member functions of the class. In python, self is required to be used as the first parameter of the function to indicate that this function is a class member function, so as to realize the difference from non-member functions in the class, you can also distinguish it from other global functions. At the same time, using self to access member variables also distinguishes member variables from local function variables and global variables. Python is designed to facilitate the classification of member variables, member functions, and other local functions and global functions. Such code allows developers to see at a glance and immediately understand those are class member functions, those are class member variables and those are function local variables. So that developers can understand the scope of the variable scope. For example, the member variable self. Data is represented in this way, while the class is not a member variable or the global variable is represented in data. A destructor is the last function called in the lifecycle of a class. All resources deleted or released are often called in this function.