• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

获取“super():无参数";一种情况下的错误,但不是类似的情况

用户头像
it1352
帮助1

问题说明

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?

正确答案

#1

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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcffifk
系列文章
更多 icon
同类精品
更多 icon
继续加载