获取“super():无参数";一种情况下的错误,但不是类似的情况 [英] Get "super(): no arguments" error in one case but not a similar case

查看:36
本文介绍了获取“super():无参数";一种情况下的错误,但不是类似的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Works(type):
    def __new__(cls, *args, **kwargs):
        print([cls,args]) # outputs [<class '__main__.Works'>, ()]
        return super().__new__(cls, args)

class DoesNotWork(type):
    def __new__(*args, **kwargs):
        print([args[0],args[:0]]) # outputs [<class '__main__.doesNotWork'>, ()]
        return super().__new__(args[0], args[:0])

Works() # is fine
DoesNotWork() # gets "RuntimeError: super(): no arguments"

据我所知,在这两种情况下,super._new__ 都接收类文字作为第一个参数,并接收一个空元组作为第二个参数.

As far as I can see, in both cases super._new__ receives the class literal as first argument, and an empty tuple as the 2nd.

那么为什么一个会报错而另一个不报错?

So why does one give an error and the other not?

推荐答案

super 的零参数形式要求包含它的方法具有明确的(即非可变参数)第一个参数.这是由 旧版本的文档 建议的(强调已添加):

The zero-argument form of super requires that the method containing it have an explicit (i.e., non-varargs) first argument. This is suggested by an older version of the docs (emphasis added):

零参数形式自动在堆栈帧中搜索类 (__class__) 和第一个参数.

The zero argument form automatically searches the stack frame for the class (__class__) and the first argument.

出于某种原因,此注释在文档的更高版本中被删除.(可能值得提出一个文档错误,因为文档对于零参数 super 的工作方式及其工作所需的条件非常模糊.)

For some reason this note was removed in later versions of the docs. (It might be worth raising a doc bug, because the docs are quite vague about how zero-argument super works and what is required for it to work.)

另请参阅此 Python 错误报告(尚未解决,甚至未明确接受为错误).结果是零参数 super 是魔术,而这种魔术在某些情况下会失败.正如错误报告中所建议的那样,如果您只想接受可变参数,则需要使用 super 的显式双参数形式.

See also this Python bug report (which is unresolved, and not clearly accepted as even a bug). The upshot is that zero-argument super is magic, and that magic fails in some cases. As suggested in the bug report, if you want to accept only varargs, you'll need to use the explicit two-argument form of super.

这篇关于获取“super():无参数";一种情况下的错误,但不是类似的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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