TypeError: super() 需要至少 1 个参数(0 给定)错误特定于任何 python 版本? [英] TypeError: super() takes at least 1 argument (0 given) error is specific to any python version?

查看:48
本文介绍了TypeError: super() 需要至少 1 个参数(0 给定)错误特定于任何 python 版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误

TypeError: super() 需要至少 1 个参数(0 给定)

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

在python2.7.11上使用此代码:

using this code on python2.7.11:

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

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

Bar()

使其工作的解决方法是:

The workaround to make it work would be:

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

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

Bar()

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

It seems the syntax is specific to python 3. So, what's the best way to provide compatible code between 2.x and 3.x and avoiding this error happening?

推荐答案

是的,0-argument 语法特定于 Python 3,请参阅 Python 3.0 的新增功能PEP 3135 -- 新超级.

Yes, the 0-argument syntax is specific to Python 3, see What's New in Python 3.0 and PEP 3135 -- New Super.

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

In Python 2 and code that must be cross-version compatible, just stick to passing in the class object and instance explicitly.

是的,有可用的backports"使 super() 的无参数版本在 Python 2 中工作(如 future 库),但这些需要一个包括 全扫描类的黑客数量层次结构 找到匹配的函数对象.这既脆弱又缓慢,根本不值得方便".

Yes, there are "backports" available that make a no-argument version of super() work in Python 2 (like the future library) but these require a number of hacks that include a full scan of the class hierarchy to find a matching function object. This is both fragile and slow, and simply not worth the "convenience".

这篇关于TypeError: super() 需要至少 1 个参数(0 给定)错误特定于任何 python 版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆