What is the class attribute of the python subclass?

soon after I came into contact with python , I encountered a little confusion when learning class inheritance, as follows:

   

so now I don"t understand, has this ever happened to any other seniors?

Apr.15,2021

1: this is because this is a class attribute, which can be accessed through a class or instance. When you create an instance of a class, all class attributes will be copied to the instance, assuming that there is
class A:

.
x = 1

a = A ()
b = A ()
at this time, APowerB gets the class attribute x from the class, and you can access x or modify it with an instance, that is, Areb, but they do not affect each other
a.x = 2
b.x = 3
at this time print A.X is 2b.x is 3Jing A.x is 1
and other attributes should be modified through the class, and all the instances created have a copy of the class attribute.

2: here you rewrite the properties of the class, your changes in the subclass can not affect the parent class, you should use the parent class to operate, otherwise it will be messed up.


what is your Python version? I tried to execute your code using Python versions of 2.7 and 3.6 , but there was an error:

  

your B.x = 3 will generally report an error. Maybe your version of Python is special. I personally understand that an attribute called B.X is created in the B class, which has nothing to do with x in A , so it directly inherits the x attribute in A . The second way to write is to overload the x attribute so that the B attribute is different from the x attribute of A .

Menu