Python在继承时使用带有超类的类属性

时间:2016-12-16 21:26:48

标签: python class inheritance class-attributes

我有一段python代码:

class A(object):
    args = [1,2]
    def __init__(self):
        print self.args

class B(A):
    args = [3,4]
    def __init__(self):
        super(B, self).__init__()
        print self.args

B()

输出结果为:

[3,4]

[3,4]

而不是

[1,2]

[3,4]

为什么从派生类调用基类的构造函数时,使用的类属性来自派生类的命名空间?有没有办法让我使用函数所在的类的类属性?

2 个答案:

答案 0 :(得分:1)

  

我有办法使用函数所在类的类属性吗?

是。按类属性名称引用它们,而不是它们的实例属性名称。也就是说,A.args,而不是self.args

class A(object):
    args = [1,2]
    def __init__(self):
        print A.args

答案 1 :(得分:0)

这里发生的是你用B的成员改写了args变量。 Python首先查看子类B,看它是否可以使用自己的A版构造函数打印args。它找到B的args并打印出该成员。

让我们看看当您将A的args重命名为arg之类的内容时会发生什么。我们现在看到预期的行为。

class A(object):
    arg = [1,2]
    def __init__(self):
        print self.arg

class B(A):
    args = [3,4]
    def __init__(self):
        super(B, self).__init__()
        print self.args
B()

输出:

[1, 2]
[3, 4]
相关问题