gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:34:31 30 4
gpt4 key购买 nike

我收到了这个错误

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com