获取“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
.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcffifk
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22