The use of classes in Python 3

In "Use of Classes in Python 2", the instance variables of the class are mentioned. In addition to the instance variables, the class can also define instance methods.

1 Definition of instance method

The code looks like this:

class MyClass:
    i = 1
    def myfunc():
        print('Hello')
    def __init__(self, num):
        self.j = num
    def show(self):
        print(self.j)

Among them, the show() method defined in the class MyClass is an instance method of the class. Similar to instance objects, instance methods belong to each instance. Therefore, the first parameter of an instance method of a class must be "self", indicating the instance that calls the method. The function of the show() method of the MyClass class is to print the instance variable j.

2 Instance method calls

It is an instance method that can be called by the method of "instance name. instance method name". The code is as follows:

c1 = MyClass(10)
c1.show()

Among them, c1 is an instance of MyClass. When the instance method show is called through c1, the value of the first parameter self of the show() method is c1. Therefore, the value printed by the show() method is actually c1.j, which is 10. Similarly, the following code

c2 = MyClass(100)
c2.show()

At this time, the value of the first parameter self of the show() method is c2, and the value printed by the show() method is actually c2.j, which is 100.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/131224164