Why does changing the value of "x" in the parent class change the value of only one child?

While experimenting with python, I realized that this code does not produce the expected result:

class Parent(object):
    x = 1

class Child1(Parent):
    pass

class Child2(Parent):
    pass


print Parent.x, Child1.x, Child2.x

Child1.x = 2
print Parent.x, Child1.x, Child2.x

Parent.x = 3
print Parent.x, Child1.x, Child2.x

The output of the above code:

1 1 1
1 2 1
3 2 3

Why the output of the last line 3 2 3, and not 3 2 1? Why does changing the value of Parent.x also change the value of Child2.x, but at the same time not changing the value of Child1.x?

thanks

+4
source share
3 answers

When you are assigned to Child1.x, you created a new attribute only for Child1. However, Child2 does not have its own attribute x, so it inherits the parent version, regardless of the current value.

+4

, Python, . Python , Child1.x, x Child1 Parent.x.

, , - ! , , , . - - , , .

+1

, script

print Parent.__dict__
print Child1.__dict__
print Child2.__dict__

You will receive a detailed overview of all members of the class and what is stored in them. The output will be

{'__dict__': <attribute '__dict__' of 'Parent' objects>, 'x': 3,    '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
{'x': 2, '__module__': '__main__', '__doc__': None}
{'__module__': '__main__', '__doc__': None}

As you can see in child1
'x': 2 was added to the dict. So child1 does not look for the value in it of the parent class, but child2 does

+1
source

Source: https://habr.com/ru/post/1617601/


All Articles