我有个错误
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之间提供兼容代码并避免发生此错误的最佳方法是什么?
可以使用future库使Python2/Python3兼容。
super函数是后端口的。
这是因为python的版本。用[python--version]检查您的python版本可能是2.7
是的,0参数语法特定于Python 3,请参见What's New in Python 3.0和PEP 3135 -- New Super。
在Python2和跨版本兼容的代码中,只需坚持显式地传递类对象和实例。
是的,有一些“backports”可以使无参数版本的
super()
在Python 2中工作(比如future
库),但是这些需要很多技巧,包括full scan of the class hierarchy来找到匹配的函数对象。这既脆弱又缓慢,根本不值得“方便”。相关问题 更多 >
编程相关推荐