class variables in python
phpcn_u1582
phpcn_u1582 2017-06-28 09:24:34
0
1
723

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_u1582
phpcn_u1582

reply all(1)
習慣沉默

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!