Python class methods

Python class methods are mainly divided into three types: instance methods, class methods and static methods.

1 instance method

A method with self as the first parameter is an instance method of the class. This method is called by an instance of the class, and Python passes the instance object calling the method to self.

The following code defines a class named A.

class A:
    def __init__(self):
        self.i = 0
    def i_f(self):
        self.i += 1

Among them, i_f() is an instance method of class A, and i is an instance variable of class A.

a1 = A()
a1.i_f()
a2 = A()

In the above code, objects a1 and a2 of class A are defined, and i_f() is called through a1. At this time, the value of the self parameter of the i_f() method is a1, and the value of a1.i becomes 1, while a2 The value of .i is still 0, as shown in Figure 1.

Figure 1 The relationship between a1 and a2

Class 2 methods

Class methods will affect the entire class, and any changes made to the class will affect all its instance objects. Class methods are generally modified with the prefix @classmethod. Similar to instance methods, the first parameter of a class method is the class itself. This parameter is generally written as cls. The code is as follows.

class A:
    i = 0
    def __init__(self):
        A.i += 1
    @classmethod
    def show_i(cls):
        print(cls.i)

Among them, i is the class variable of A. Every time an instance object of A is generated, the class variable i will be incremented by 1. show_i() is modified by @classmethod, so it is a class method of A. This method can print out the number of times class A is instantiated.

a1 = A()
a2 = A()
a3 = A()
A.show_i()

In the above code, because A is instantiated three times, the printed result is 3.

3 static methods

Static methods are decorated with @staticmethod, which will neither affect the class nor the objects of the class. The code is as follows

class A:
    def __init__(self):
        self.i = 0
    @staticmethod
    def set_i():
        i = 1

Among them, the set_i() method of class A is a static method. It can be seen that the static method has neither self parameter nor cls parameter.

a1 = A()
A.set_i()

At this time, although the set_i() method is called, the value of a1.i is still 0.

It should be noted that static methods can also be modified without @staticmethod.

おすすめ

転載: blog.csdn.net/hou09tian/article/details/132685996