Are the variables in the class the same as self.var1 in the function? Why are they the same?
class test:
var1=2
def __init__(self):
print self.var1
print self.var1 is test.var1
if __name__=="__main__":
test2=test()
What happens after the function is run is
root@lpp-ThinkPad-T420:~/python_code# python test6.py
2
True
Why is the class variable var1 here self.var1? What is the reason?
var1
is a class variable,self.var1
is an instance variable. When you initialize the class totest2
,__init__
looks forvar1
of its own instance. If it is not found, then go to the base class to find it. , that is, I searched intest
, and I just found it, so I returned it to you directlyIf you want to go deeper, you can search on Google for relevant knowledge about
class variables/instance variables
andpython descriptor