Get “super(): no arguments” error in one case but not a similar case

为君一笑 提交于 2020-01-12 14:26:26

问题


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"

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:


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):

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

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.)

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.



来源:https://stackoverflow.com/questions/39312553/get-super-no-arguments-error-in-one-case-but-not-a-similar-case

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!