This article explains the example in the form of class variables and member variables of usage python for Python programming has a certain reference value. Share to you for your reference. details as follows:
Look at the following 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, can be called directly by the class name, you can also object to call;
val2 is a member variable that can be called by the object class, here you can see a certain member variables are given in the form of self. because the meaning of the self is to represent the instance of the object;
val3 is not a member variable, it's just a local variable inside a function FCN;
. VAL4 and val5 also not a member variable, although is self given, but did not initialize in the constructor.
Look at the following code (behind the # sign are the results):
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
It can be found: different python C ++ class variables and static variables are not shared by all object classes. The class itself has its own class variables (saved in memory), a TestClass class when an object is constructed, will present a copy of the class variable to this object, the value of the current class variable is how much, get a copy of this object class variables the value is the number; moreover, the value of the variable to modify the class through an object, and does not affect other objects of the class variable, because everyone has their own copy, but does not affect the value of the class itself owned by that class variables; only class themselves can change the value of the class itself has class variables
here we recommend the python learning sites, click to enter , to see how old the program is to learn! From basic python script, reptiles, django, data mining, programming techniques, work experience, as well as senior careful study of small python partners to combat finishing zero-based information projects! The method has timed programmer Python explain everyday technology, to share some of the learning and the need to pay attention to small details