子类 - 超类的参数 [英] Subclass - Arguments From Superclass

查看:145
本文介绍了子类 - 超类的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何在Python中的子类和超类之间传递参数感到困惑。考虑以下类结构:

I'm a little confused about how arguments are passed between Subclasses and Superclasses in 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

我在哪里麻烦是理解如何在超类和子类之间传递参数。是否有必要重新列出Subclass初始化程序中的所有超类参数?新的,仅限Subclass,在哪里指定参数?当我尝试使用上面的代码来实例化一个子类时,它只需要1个参数,而不是我列出的原始4(包括self)。

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? Where would new, Subclass only, arguments be specified? 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.

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


推荐答案

没有神奇的事情发生! __ init __ 方法与其他方法一样。您需要在子类初始化器中显式获取所需的所有参数,并将它们传递给超类。

There's no magic happening! __init__ methods work just like all others. 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

当你打电话给 Subclass(arg1,arg2,arg3) Python只会调用 Subclass .__ init __(< the instance>,arg1,arg2,arg3)。它不会神奇地尝试将某些参数与超类匹配,而某些参数则与子类相匹配。

When you call Subclass(arg1, arg2, arg3) Python will just call 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.

这篇关于子类 - 超类的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆