简体   繁体   English

子类 - 超类的参数

[英]Subclass - Arguments From Superclass

I'm a little confused about how arguments are passed between Subclasses and Superclasses in Python. 我对Python中子类和超类之间如何传递参数感到困惑。 Consider the following class structure: 考虑以下类结构:

class Superclass(object):
    def __init__(self, arg1, arg2, arg3):
        #Inilitize some variables
        #Call some methods

class Subclass(Superclass):
    def __init__(self):
        super(Subclass, self).__init__()
        #Call a subclass only method

Where I'm having trouble is understanding how arguments are passed between the Superclass and Subclass. 我遇到麻烦的地方是理解超类和子类之间如何传递参数。 Is it necessary to re-list all the Superclass arguments in the Subclass initializer? 是否有必要重新列出Subclass初始化程序中的所有Superclass参数? Where would new, Subclass only, arguments be specified? 新的,仅限Subclass,在哪里指定参数? When I try to use the code above to instantiate a Subclass, it only expects 1 argument, not the original 4 (including self) I listed. 当我尝试使用上面的代码实例化一个子类时,它只需要1个参数,而不是我列出的原始4(包括self)。

TypeError: __init__() takes exactly 1 argument (4 given)

There's no magic happening! 没有魔法发生! __init__ methods work just like all others. __init__方法与其他方法一样工作。 You need to explicitly take all the arguments you need in the subclass initialiser, and pass them through to the superclass. 您需要在子类初始化器中显式获取所需的所有参数,并将它们传递给超类。

class Superclass(object):
    def __init__(self, arg1, arg2, arg3):
        #Initialise some variables
        #Call some methods

class Subclass(Superclass):
    def __init__(self, subclass_arg1, *args, **kwargs):
        super(Subclass, self).__init__(*args, **kwargs)
        #Call a subclass only method

When you call Subclass(arg1, arg2, arg3) Python will just call Subclass.__init__(<the instance>, arg1, arg2, arg3) . 当你调用Subclass(arg1, arg2, arg3) Python将只调用Subclass.__init__(<the instance>, arg1, arg2, arg3) It won't magically try to match up some of the arguments to the superclass and some to the subclass. 它不会神奇地尝试将一些参数与超类相匹配,而某些参数则与子类相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM