SoFunction
Updated on 2025-03-02

Detailed explanation of the usage and understanding examples of __init__ in Python

Usage and understanding of __init__ in Python

Defining classes in Python often uses __init__ functions (methods). The first thing to understand is that functions starting with two underscores declare that the property is private and cannot be used or accessed outside the class. The __init__ function (method) supports initialization of a class with parameter, and can also declare properties of the class (variables in the class). The first parameter of the __init__ function (method) must be self, and subsequent parameters are defined by yourself.

It is difficult to understand the text, and it is easy to understand this concept through the following examples:

For example, we define a Box class with three attributes: width, height, and depth, and a method for calculating volume:

#!/usr/bin/python
# -*- coding utf-8 -*-
#Created by Lu Zhan
 
class Box:
    def setDimension(self, width, height, depth):
         = width
         = height
         = depth
 
    def getVolume(self):
        return  *  * 
 
b = Box()
(10, 20, 30)
print(())

We define the setDimension method in the Box class to set the properties of the Box, which is too cumbersome. Using the special method of __init__(), you can easily define the properties of the class yourself. The __init__() method is also called a constructor.

#!/usr/bin/python
# -*- coding utf-8 -*-
#Created by Lu Zhan
 
class Box:
    #def setDimension(self, width, height, depth):
    #    = width
    #    = height
    #    = depth
    def __init__(self, width, height, depth):
         = width
         = height
         = depth
 
    def getVolume(self):
        return  *  * 
 
b = Box(10, 20, 30)
print(())

Supplement: Python __init__() class constructor

When creating a class, we can manually add a __init__() method, which is a special class instance method called a constructor (or constructor).

The constructor is used when creating an object, and the Python interpreter automatically calls it whenever an instance object of a class is created. In Python classes, the syntax format for manually adding constructors is as follows:

def __init__(self,...):
    Code block

Note that in the method name of this method, there are 2 underscores at the beginning and end of each, and there cannot be spaces in the middle. Many of the methods in Python that start with double underscores and end with double underscores have special significance and will be explained to you one by one in the future.

In addition, the __init__() method can contain multiple parameters, but must contain a parameter named self and must be the first parameter. In other words, the class constructor must have at least one self parameter. For example, still taking the FirstDemo class as an example, the code to add the constructor is as follows:

class TheFirstDemo:
    '''This is the first class to learn Python definition'''
    #Construction method    def __init__(self):
        print("Call the constructor")
    #A class attribute is defined below    add = ''
    # The following defines a say method    def say(self, content):
        print(content)

Note that even if you don't add any constructors to the class manually, Python will automatically add a constructor to the class that only contains the self parameter.

The __init__() constructor that only contains the self parameter, also known as the default constructor of the class.

After the above code, add the following code directly to the header (not indented):

zhangsan = TheFirstDemo()

The meaning of this line of code is to create a TheFirstDemo class object named zhangsan. Run the code and you can see the following results:

Calling the constructor

Obviously, when creating the zhangsan object, the __init__() constructor we created manually is called implicitly.

Not only that, in the __init__() constructor, in addition to the self parameter, some parameters can be customized, and the parameters are divided using comma "," to be separated. For example, the following code specifies 2 additional parameters when creating the __init__() method:

class CLanguage:
    '''This is a class that learns Python definition'''
    def __init__(self,name,add):
        print(name,"The URL is:",add)
#Create an add object and pass parameters to the constructoradd = CLanguage("I","//")

Note that since the class constructor method is called when creating an object, if the constructor has multiple parameters, the parameters need to be passed manually. The delivery method is as shown in the code (there will be explained in detail in the subsequent chapters).

Run the above code and the execution result is:
My website is: //

It can be seen that although there are three parameters in the construction method: self, name, and add, only name and add that need to be passed. That is to say, self does not need to pass parameters manually.

Regarding the self parameter, the subsequent chapters will introduce it in detail. Here you only need to know that when creating a class object, there is no need to pass parameters to self.

This is the article about the usage and understanding of __init__ in Python. For more related content on __init__ in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!