TypeError:super()至少接受1个参数(给定0个参数)error是否特定于任何python版本?

2024-05-15 13:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个错误

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之间提供兼容代码并避免发生此错误的最佳方法是什么?


Tags: 代码selfobjectfooinitdef错误bar
3条回答

可以使用future库使Python2/Python3兼容。

super函数是后端口的。

这是因为python的版本。用[python--version]检查您的python版本可能是2.7

In 2.7 use this [ super(baseclass, self).__init__() ]

class Bird(object):
    def __init__(self):
        print("Bird")

    def whatIsThis(self):
        print("This is bird which can not swim")

class Animal(Bird):
    def __init__(self):
        super(Bird,self).__init__()
        print("Animal")

    def whatIsThis(self):
        print("THis is animal which can swim")

a1 = Animal()
a1.whatIsThis()

> In 3.0 or more use this [ super().__init__()]

class Bird(object):
    def __init__(self):
        print("Bird")

    def whatIsThis(self):
        print("This is bird which can not swim")

class Animal(Bird):
    def __init__(self):
        super().__init__()
        print("Animal")

    def whatIsThis(self):
        print("THis is animal which can swim")

a1 = Animal()
a1.whatIsThis()

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

在Python2和跨版本兼容的代码中,只需坚持显式地传递类对象和实例。

是的,有一些“backports”可以使无参数版本的super()在Python 2中工作(比如future库),但是这些需要很多技巧,包括full scan of the class hierarchy来找到匹配的函数对象。这既脆弱又缓慢,根本不值得“方便”。

相关问题 更多 >