The examples in this article illustrate Python's class variables and member variable usage, which is of some reference value to Python programming. Share to everyone for your reference. Specifically as follows:
Let's take a look at the following code:
Class TestClass (object):
val1 =
def __init__ (self):
self.val2 =
def fcn (self,val = =):
Val3 =
Self.val4 = val
self.val5 = +
if __name__ = = ' __main__ ':
inst = TestClass ()
print TESTCL Ass.val1
print inst.val1
print inst.val2
print inst.val3
print inst.val4
print INST.VAL5
Here, the VAL1 is a class variable that can be called directly by the class name, or it can be invoked by an object;
Val2 is a member variable that can be invoked by the object of the class, where you can see that the member variable must be given in the form of self, because the meaning of self is to represent the instance object;
Val3 is not a member variable, it is only a local variable within the function FCN;
Val4 and VAL5 are also not member variables, although they are given by self, but are not initialized in constructors.
Take a look at the following code (#号后面的是运行结果):
Inst1 = TestClass ()
inst2 = TestClass ()
print Testclass.val1 #
print inst1.val1 #
Inst1.val1 = 1000
print inst1.val1 # 1000
print Testclass.val1 # testclass.val1
=2000
Print Inst1.val1 # 1000
print Testclass.val1 #
print inst2.val1 # inst3
= TestClass ()
print Inst3.val1 # 2000
You can see that Python's class variables are different from static variables in C + + and are not shared by all objects of the class. The class itself has its own class variable (stored in memory), and when an object of a TestClass class is constructed, copies the current class variable to the object, the value of the current class variable, and the value of the class variable copied by the object ; Modifying a class variable with an object does not affect the value of the class variable of the other object, since everyone has their own copy, not to mention the value of the class variable owned by the class itself, and only the class itself can change the value of the class variable owned by the class itself .
I hope the examples described in this article will help you to understand and Master Python's class variables and member variable usages.