我是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/