【问题标题】:Python using class attributes with super when inheritingPython在继承时使用带有super的类属性
【发布时间】:2016-12-16 21:26:48
【问题描述】:

我有一段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]

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

【问题讨论】:

  • self.attribute 首先查看对象的“直接”属性,然后遍历继承链直到找到该属性。当您执行self.args 时,它首先“查看自我”,然后查看 B 并找到属性。

标签: python class inheritance class-attributes


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    这里发生的情况是,您实际上已经用 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]
    

    【讨论】:

      猜你喜欢
      • 2022-12-18
      • 2019-05-15
      • 2016-07-08
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多