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

Nag*_*aga 8 python class python-3.x

我是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__()
Run Code Online (Sandbox Code Playgroud)

错误:

    __props__ = super().__props__ + (
RuntimeError: super(): no arguments
Run Code Online (Sandbox Code Playgroud)

Pat*_*ugh 4

您可以定义一个初始化类__init_subclass__的方法。每次创建 of 的子类时都会调用此方法,我们可以使用它来修改该类继承的对象,并使用作为类定义的一部分传递的可选参数。 ParentChild.__props__Parent__props____props__

class Parent:
    __props__ = (('a', str, 'a var'), ('b', int, 'b var'))
    def __init_subclass__(cls, __props__=(), **kwargs):
        super().__init_subclass__(**kwargs)
        cls.__props__ = cls.__props__ + __props__

class Child(Parent, __props__=(('c', str, 'foo'),)):
    pass

print(Child.__props__)
# (('a', <class 'str'>, 'a var'), ('b', <class 'int'>, 'b var'), ('c', <class 'str'>, 'foo'))

class GrandChild(Child, __props__=(('d', float, 'd var'),)):
    pass

print(GrandChild.__props__)
# (('a', <class 'str'>, 'a var'), ('b', <class 'int'>, 'b var'), 
#  ('c', <class 'str'>, 'foo'), ('d', <class 'float'>, 'd var'))
Run Code Online (Sandbox Code Playgroud)