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

标签 python python-2.7 class arguments super

<分区>

我问这个问题是因为我在 SO 上搜索过关于这个主题的每一个其他页面似乎都退化为过于简单的案例或关于超出范围的细节的随机讨论。

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

最佳答案

您的基类必须继承自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

关于python - 如何在 Python 2.7 中使用带参数的 super()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38528215/

相关文章:

python - 在子进程中调用包装器脚本

c++ - 使用类的属性制作二维数组,更改值时遇到问题

python - 如何按小时对数值进行分组?

python - 在 Python 中将管道分隔文本文件的文件夹转换为 CSV

python - 根据特定键合并字典列表

python - 使用简单绘图脚本时出现属性错误

python - 如何找到多个集合和列表之间的交集?

python - Enthought Python 中的线程 FFT

c++ - 在公共(public)成员函数调用中引用私有(private)成员变量的更安全方法?

Python 类基础