How to understand and use the __init__ function and parameter self in Python?

How to understand and use the __init__ function and parameter self in Python?

Anyone who has studied Python knows the syntax of self and __init__, but relying on rote memorization to force yourself to understand is not a good way. Today, let’s go back and see how the __init__ function and the parameter self can be understood and used more flexibly. .

To recap:

The class class contains:

  • Class attributes: variables involved in the class;
  • Class methods: functions in the class;

1. Understand the __init__ function (method)

The __init__ function (method) is often used to define classes in Python, but the function and meaning of the __init__() method are not well understood.

The init() method is of great significance in two aspects:

① Initialized during the object life cycle. Each object must be correctly initialized before it can work properly.

② The init() parameter value can have many forms.

__init__ is a bit like the constructor in C# and is called immediately after the class instance is created.

class Student:
    def __init__(self,number):
        self.number=number 
    def student_number(self):
        print('number:',self.number)
        
student=Student(34)
student.student_number()

Here, we define the __init__ method to have a parameter number and self, which creates a new field number.

In this process, the data is encapsulated in the class through self.number=number, and the call is made directly through the class Student.

1) Use the __init__ function (method)

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 the initialization of a parameterized class and can also be used to declare attributes of the class (variables in the class).

The first parameter of the init function (method) must be self (self is an idiom, a conventional thing), and the subsequent parameters can be freely defined, which is no different from defining a function.

2) Then why must we define the init() method? Look at an example:

What happens if we don't define a class using the init() method?

Define a rectangle class with the purpose of finding the perimeter and area;

class Rectangle():
    def getPeri(self,a,b):
        return (a + b)*2
    def getArea(self,a,b):
        return a*b

rect = Rectangle()
print(rect.getPeri(3,4))
print(rect.getArea(3,4))
print(rect.__dict__)

result

14
12
{}

As you can see from the above example, we did not define the init() method in the class, but we can also get similar requirements. As a result, the perimeter and area of ​​the rectangle instance rect are returned.

However, when we look at the attributes of this instance through print(rect.dict), it turns out to be empty. I have defined a rectangle. Logically speaking, its attributes should be its length and width.

But it doesn't, which is why init() is not defined.

Moreover, when instantiating the object, the rect = Rectangle() parameter is empty, and the values ​​​​of a and b are not specified. They are only specified when the function is called.

Moreover, the parameters of each method defined in the class have a and b. This is obviously a waste of emotion. Just specify the method directly in the class.

Therefore, it is necessary to define the init() method in the class, so that when creating an instance, you need to bind attributes to the instance, and it is also convenient for the definition of methods (functions) in the class.

Define a class using the init() method

Do it again using the above example

class Rectangle():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def getPeri(self):
        return (self.a + self.b)*2
    def getArea(self):
        return self.a * self.b

rect = Rectangle(3,4)
print(rect.getPeri())
print(rect.getArea())
print(rect.__dict__)

result

14
12
{'a': 3, 'b': 4}

From the above results, we can see that after init() is defined, each instance created has its own attributes and can directly call functions in the class.

 

Guess you like

Origin blog.csdn.net/z1521695011/article/details/131210172