python - 类型错误 : super() takes at least 1 argument (0 given) error is specific to any python version?

标签 python python-2.7 python-2.x

我收到了这个错误

TypeError: super() takes at least 1 argument (0 given)

在python2.7.11上使用这段代码:

class Foo(object):
    def __init__(self):
        pass

class Bar(Foo):
    def __init__(self):
        super().__init__()

Bar()

使其工作的解决方法是:

class Foo(object):
    def __init__(self):
        pass

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()

Bar()

似乎该语法特定于 python 3。那么,在 2.x 和 3.x 之间提供兼容代码并避免发生此错误的最佳方法是什么?

最佳答案

是的,0 参数语法特定于 Python 3,请参阅 What's New in Python 3.0PEP 3135 -- New Super .

在 Python 2 和必须跨版本兼容的代码中,只需坚持显式传入类对象和实例即可。

是的,有可用的“反向移植”使 super() 的无参数版本在 Python 2 中工作(如 future 库),但这些需要包含 full scan of the class hierarchy 的 hack 数量找到匹配的函数对象。这既脆弱又缓慢,根本不值得“方便”。

关于python - 类型错误 : super() takes at least 1 argument (0 given) error is specific to any python version?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38963018/

相关文章:

python - Django 管理样式 : Change "Site administration" and subheadings

python - 用于上传和下载的 PYSFTP 脚本

python - 从对象扩展类

python - 基维 : how to add vertical scrollbar in boxlayout

python - 为什么 Python 的 dict.keys() 返回一个列表而不是一个集合?

python - 如何将新列表附加到现有 CSV 文件?

无限循环内的 Raspberry Pi 用户输入中的 Python 在遇到许多输入时会丢失输入

python - 在 Anaconda 环境中使用 pip 安装模块

arrays - 索引错误 : index 10 is out of bounds for axis 0 with size 10

python - Django索引错误: Pop from empty list