python - Python 中 super().__init__() 和显式父类(super class) __init__() 之间的行为差​​异

标签 python python-3.x inheritance super keyword-argument

我在使用 super().__init__() 之间发现了无法解释的行为差异并在我的代码中显式调用父类(super class)构造函数。

class IPElement(object):

def __init__(self, ip_type='IPv4'):
    self.ip_type = ip_type

class IPAddressSimple(IPElement):

    def __init__(self, ip_name, ip_type='IPv4'):
        self.ip_name = ip_name
        super().__init__(self, ip_type=ip_type)

在这里,行 super().__init__(self, ip_type=ip_type)导致类型错误:
TypeError: __init__() got multiple values for argument 'ip_type'

当我将调用更改为通过 ip_type按位置(例如 super().__init__(self, ip_type) 我收到不同类型的错误:
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

这些错误对我来说都没有意义,当我替换 super() 时使用父类(super class)的显式名称,一切都按预期工作。以下工作正常,按位置传递 ip_type 也是如此:
class IPAddressSimple(IPElement):

        def __init__(self, ip_name, ip_type='IPv4'):
            self.ip_name = ip_name
            IPElement.__init__(self, ip_type=ip_type)

我当然可以使用显式调用父类(super class) __init__必要时的方法,但我想了解为什么super()不在这里工作。

最佳答案

super()已经通过 self陪着你。 super(IPAddressSimple)不会知道 self ,因此在这种情况下,您需要调用 super(IPAddressSimple).__init__(self, ip_type) .但是super() (这是 super(IPAddressSimple, self) 的语法糖)知道 self并处理它,所以你应该只通过 ip_type手动。

关于python - Python 中 super().__init__() 和显式父类(super class) __init__() 之间的行为差​​异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27566391/

相关文章:

php - 管理一个应用的多个专业版本的最佳实践

c++ - 为什么 C++ 不允许继承友元?

python - 有理由在python中用try try语句包装kwargs.get()吗?

python - 反向未找到 Django

python - 使用 ctypes 从共享库映射全局变量

python-3.x - 带有 numpy 数组的 Python Pandas 字典

c++ - 为什么我必须通过this指针访问模板基类成员?

python - 用asyncore实现gethostbyaddr()

python-3.x - 如何将 AWS 托管策略附加到 cloudformation 和对流层中的角色

Python Google Drive API - 获取我的云端硬盘文件夹的 ID