面向对象静态变量代码题

  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

原因:对于父类中的静态变量,子类对象只能查看,不能修改,而child1.x = 2是在外部对child1类添加了一个属性

打印一下:print(Child1.__dict__)  print(Parent.__dict__)

原文地址:https://www.cnblogs.com/apollo1616/p/10206141.html