【问题标题】:How to use super() with arguments in Python 2.7? [duplicate]如何在 Python 2.7 中使用带有参数的 super()? [复制]
【发布时间】:2016-11-26 11:05:04
【问题描述】:

我问这个问题是因为我在谷歌上搜索过的关于该主题的所有其他页面似乎都变成了过于简单的案例或对超出范围的细节的随机讨论。

class Base:
    def __init__(self, arg1, arg2, arg3, arg4):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
        self.arg4 = arg4

class Child(Base):
    def __init__(self, arg1, arg2, arg3, arg4, arg5):
        super(Child).__init__(arg1, arg2, arg3, arg4)
        self.arg5 = arg5

这是我尝试过的。我被告知我需要使用类型而不是 classobj,但我不知道这意味着什么,Google 也没有提供帮助。

我只是想让它工作。在 Python 2.7 中这样做的正确做法是什么?

【问题讨论】:

    标签: python python-2.7 class arguments super


    【解决方案1】:

    您的基类必须继承自object(新样式类)并且对super 的调用应该是super(Child, self)

    您也不应该将arg5 传递给Base__init__

    class Base(object):
        def __init__(self, arg1, arg2, arg3, arg4):
            self.arg1 = arg1
            self.arg2 = arg2
            self.arg3 = arg3
            self.arg4 = arg4
    
    class Child(Base):
        def __init__(self, arg1, arg2, arg3, arg4, arg5):
            super(Child, self).__init__(arg1, arg2, arg3, arg4)
            self.arg5 = arg5
    

    【讨论】:

    • 如果基类没有从对象继承怎么办?
    • 不,我的意思是人们是怎么做到旧式的?
    • @user6596353 使用类名,但这不是推荐的方法:Base.__init__(arg1, arg2, arg3, arg4)
    猜你喜欢
    • 2017-02-25
    • 2020-04-06
    • 1970-01-01
    • 2013-07-27
    • 2022-06-23
    • 1970-01-01
    • 2013-01-16
    • 2017-11-04
    • 1970-01-01
    相关资源
    最近更新 更多