Python 为什么更改';x';在父类中,是否只更改一个子类的值?

Python 为什么更改';x';在父类中,是否只更改一个子类的值?,python,class,inheritance,theory,Python,Class,Inheritance,Theory,在试用python时,我意识到这段代码并没有产生我预期的输出: 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

在试用python时,我意识到这段代码并没有产生我预期的输出:

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
上述代码的输出为:

1 1 1
1 2 1
3 2 3
为什么最后一行的输出是
3 2 3
而不是
3 2 1
?为什么更改Parent.x的值也会更改Child2.x的值,但同时不会更改Child1.x的值


感谢当您分配给
Child1.x
时,您仅为Child1创建了一个新属性。但是,Child2没有自己的
x
属性,因此它继承父版本,不管当前的值是什么。

根据Python类中定义的属性,它具有写时复制行为。由于Python中的每个变量都是一个引用,因此在将新值赋给
Child1.x
之前,
Child1
中的
x
指的是
Parent.x
的值


事实上,你试图做的是在一般的坏习惯!在真正知道自己在做什么之前,不应该使用计划稍后修改的类定义变量进行放置。事实上,您的示例是对面向对象范例的滥用,因为您应该使用类的实例,而不是类本身。

如注释中所示,这是一个更广泛的答案 如果您将此添加到脚本的末尾

print Parent.__dict__
print Child1.__dict__
print Child2.__dict__
您可以详细了解类的所有成员以及存储在其中的内容。 输出将是

{'__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}
{''x':3','x':模块:''u'u':''u'u'u'u'u'u'u'u'u'u'u'u'u'u'u'u'u'u'u','u'u'u'u'u'weakref'u':,'u'u'u'u'u'u'u'u doc':无}
{'x':2','uuuuuuuuuu模块:''uuuuuu主''uuuuuuuuu',''uuuuuuu文档''uuuuuuuuu':无}
{“模块”:“主模块”、“文档”:无}
正如您在child1中看到的那样
“x”:2
已添加到dict中。因此child1不会在其父类中查找值,但child2会查找值,因为您已将
x
的值更改为3 ie
parent.x=3
。。其中child2从父级获取x。如果删除Child1.x=2,则它将是3,但由于已将其设置为子级,因此它将不再访问父级类的值