我收到了这个错误
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.0和 PEP 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/