First 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 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 directly by the class name, or it can have objects to invoke;
Val2 is a member variable that can be called by the object of the class, and here you can see that the member variable must be given in the form of self, because self means to represent an instance object;
Val3 is not a member variable, it is just a local variable inside the function FCN;
Val4 and VAL5 are also not member variables, although they are given as self. But are not initialized in the constructor.
And look at the following code (#号后面的是运行结果):
Inst1 = TestClass () inst2 = TestClass () print Testclass.val1 # print inst1.val1 # Inst1.val1 = inst1.val1 # Print Testclass.val1 # Testclass.val1 =2000 Print Inst1.val1 # testclass.val1 # print inst2.val1 # inst3 = TestClass ( ) print Inst3.val1 # 2000
you can see that Python's class variables are different from C + + static variables 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 the TestClass class is constructed, a copy of the current class variable is copied to the object, the value of the current class variable, and the value of the class variable that the object is copied from, and the class variable is modified by the object. Does not affect the value of the class variables of other objects, 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 the class variable owned by the class itself.
Python class variables and member variables