The use of classes in Python 2

As mentioned in "Using Classes in Python 1", class variables and methods are divided into class variables (class methods) and instance variables (instance methods). So what is the relationship between these two variables (methods)? Take the MyClass class mentioned in "Using Classes in Python 1" as an example, its code is as follows:

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

Among them, i and myfunc are class variables and class methods of MyClass, and j is a member variable of MyClass.

1 Accessing class variables by instance name

Class variables are common to each instance, and instance variables are unique to each instance.

After defining MyClass, continue to define two instances of this class, c1 and c2, the code is as follows:

c1 = MyClass(10)
c2 = MyClass(100)

As mentioned in "Using Classes in Python 1", class variables can be used in the form of "class name. variable name". In addition to this method, class variables can also be used in the way of "instance name.variable name", the code is as follows:

print(c1.i)
print(c2.i)

Because all instances share the class variable, the output of the above code is 1.

When the class variable is modified by the class name, the code is as follows

MyClass.i = 2
print(c1.i)
print(c2.i)

Because the class variable is shared by each instance, the output at this time is 2.

2 Modify class variables by instance name

In "1 Accessing class variables through instance names", it is mentioned that class variables can be used in the way of "instance name.variable name", and class variables can also be modified in the same way. The code looks like this:

c1.i = 2
print(c1.i)

The output at this time is 2.

It should be noted that when modifying a class variable through the method of "instance name. variable name", it is equivalent to recreating a new "instance variable" for the instance without affecting the real class variable. The code is as follows :

c1.i = 2
print(MyClass.i)
print(c2.i)

Both outputs at this time are "1".

3 Instance variables cannot be used and modified by the class name

Class variables can be used and modified by the instance name, but not vice versa, that is to say, instance variables cannot be used and modified by the method of "class name.variable name".

print(MyClass.j)

The above code will report an error, and the error message is "AttributeError: type object 'MyClass' has no attribute 'j'", indicating that the MyClass class does not have a class variable named "j".

Guess you like

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