在python中访问超级

在python中访问超级

本文介绍了在python中访问超级(父)类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to python. Im trying to access the parent class variable in child class using super() method but it throws error "no arguments". Accessing class variable using class name works but i like to know whether it is possible to access them using super() method.

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


推荐答案

您可以定义 Parent __ init_subclass __ 方法/ code>初始化 Child .__ props __ 的类,每次 Parent 的子类时都会调用此方法。是crea ted,我们可以使用它来修改该类继承的 __ props __ ,并使用一个可选的 __ props __ 参数作为类定义。

You could define an __init_subclass__ method of the Parent class that initializes Child.__props__. This method is called every time a subclass of of Parent is created, and we can use it to modify the __props__ that class inherits with an optional __props__ argument passed as part of the class definition.

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'))

这篇关于在python中访问超级(父)类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:43