如何在 Python 2.7 中使用带参数的 super()?

How to use super() with arguments in Python 2.7?

我问这个问题是因为我 Googled 关于这个主题的每一个其他页面似乎都变成了过于简单的案例或对超出范围的细节的随机讨论。

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 中这样做的正确做法是什么?

您的基础 class 必须继承自 object(新样式 class)并且对 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