Home  >  Q&A  >  body text

class variables in python

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?

phpcn_u1582phpcn_u15822669 days ago733

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-06-28 09:26:34

    var1 is a class variable, self.var1 is an instance variable. When you initialize the class to test2, __init__ looks for var1 of its own instance. If it is not found, then go to the base class to find it. , that is, I searched in test, and I just found it, so I returned it to you directly

    If you want to go deeper, you can search on Google for relevant knowledge about class variables/instance variables and python descriptor

    reply
    0
  • Cancelreply