Python's sample tutorial on the use of class variables and member variables
- 2020-04-02 14:00:35
- OfStack
This article illustrates the usage of python class variables and member variables in the form of an example, which has certain reference value for python programming. Share with you for your reference. The details are as follows:
Take a look at this code:
class TestClass(object):
val1 = 100
def __init__(self):
self.val2 = 200
def fcn(self,val = 400):
val3 = 300
self.val4 = val
self.val5 = 500
if __name__ == '__main__':
inst = TestClass()
print TestClass.val1
print inst.val1
print inst.val2
print inst.val3
print inst.val4
print inst.val5
Here, val1 is a class variable that can be called either directly by the class name or by an object.
Val2 is a member variable, which can be called by the object of the class. Here we can see that the member variable must be given in the form of self.
Val3 is not a member variable, but a local variable inside the function FCN.
Neither val4 nor val5 are member variables, given as self.but not initialized in the constructor.
Take a look at the following code (after the # sign is the result of the run) :
inst1 = TestClass()
inst2 = TestClass()
print TestClass.val1 # 100
print inst1.val1 # 100
inst1.val1 = 1000
print inst1.val1 # 1000
print TestClass.val1 # 100
TestClass.val1 =2000
print inst1.val1 # 1000
print TestClass.val1 # 2000
print inst2.val1 # 2000
inst3 = TestClass()
print inst3.val1 # 2000
You can see that python class variables are different from C++ static variables and are not Shared by all objects in the class. The class itself has its own class variable (stored in memory). When the object of a TestClass class is constructed, it will copy the current class variable to the object. What is the value of the current class variable? Moreover, modifying a class variable through an object does not affect the value of a class variable of another object, because everyone has their own copy, and it does not affect the value of the class variable owned by the class itself. Only the class itself can change the value of a class variable owned by the class itself.
Hopefully, the examples described in this article will help you understand and master the usage of Python's class and member variables.