python - 在python中访问超(父)类变量

标签 python python-3.x class

我是python的新手。我试图使用 super() 方法访问子类中的父类变量,但它抛出错误“无参数”。使用类名访问类变量有效,但我想知道是否可以使用 super() 方法访问它们。

class Parent(object):
        __props__ = (
            ('a', str, 'a var'),
            ('b', int, 'b var')
        )

        def __init__(self):
            self.test = 'foo'

class Child(Parent):
    __props__ = super().__props__ + (
        ('c', str, 'foo'),
    ) # Parent.__props__


    def __init__(self):
        super().__init__()

错误:
    __props__ = super().__props__ + (
RuntimeError: super(): no arguments

最佳答案

super当您拥有它的实例时,可以帮助您获得父类。据我所知,在没有实例的情况下,没有简单的方法可以在类级别执行此操作,就像您尝试做的那样。我能想到的唯一方法是显式引用父类:

class Child(Parent):
    __props__ = Parent.__props__ + ...

为了进一步澄清,有两个基本问题:
  • super()super(Child, self) 的语法糖,或更一般地说,super(type(self), self) .由于没有self你在哪里使用它,它没有意义。
  • 连类Child不存在于 super()正在被调用。它仍在定义过程中,因此即使有 super(Child, self) 也是无效的语法。 (去试试吧,我可以等),因为Child还不是一回事。

  • 因此,您需要明确引用父类,就像我上面展示的那样。

    关于python - 在python中访问超(父)类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53189980/

    相关文章:

    Java 内部类和嵌套类

    Python numpy 添加错误

    python - 与 sympy 集成

    python - 如何知道我在 conda(和 pip)中安装了哪些软件包?

    python-3.x - 如何定义可订阅的 `NewType`,例如 `List[int]`

    python - 遍历 Python 中的间隔列表并返回奇数和偶数?

    PHP 仅包含外部类一次

    c++ - 在 C++ 中设置 vector

    python - 当我尝试删除对象时出现 "list out of index range"错误

    python - 在循环中转换 Pandas Dataframes 值