super() 在 Python 3 中没有参数基本上是对其基于参数的版本的破解。
当super() 没有参数时,它会获取第一个参数,即使用名为__class__ 的特殊单元变量的类,对于第二个参数,它将从堆栈中获取第一个局部变量(这将是函数的第一个参数)。
如果是__new__,它可以同时获得(__class__ 和cls)并且工作正常。
但在这种情况下,例如,除了__class__ 之外没有第二个变量可用,因此它失败了。
class A:
@staticmethod
def func():
super().func() # super(__class__, <missing>).func()
A().func() # RuntimeError: super(): no arguments
现在,如果我们将其更改为接受一个参数,那么情况就会改变:
class A:
@staticmethod
def func(foo):
super().func()
# This fails because super(B, 1).func() doesn't make sense.
A().func(1) # TypeError: super(type, obj): obj must be an instance or subtype of type
# Works! But as there's no parent to this class with func() it fails as expected.
A().func(A()) # AttributeError: 'super' object has no attribute 'func'
因此,唯一的解决方案是在您的情况下使用 super() 明确说明:
super(C, C).funcC()
一般来说,我不确定为什么在 staticmethod 的情况下实现不能产生异常并使用__class__ 作为两个参数以使其工作。
相关CPython code:
static int
super_init(PyObject *self, PyObject *args, PyObject *kwds)
{
superobject *su = (superobject *)self;
PyTypeObject *type = NULL;
PyObject *obj = NULL;
PyTypeObject *obj_type = NULL;
if (!_PyArg_NoKeywords("super", kwds))
return -1;
if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
return -1;
if (type == NULL) {
/* Call super(), without args -- fill in from __class__
and first local variable on the stack. */
PyFrameObject *f;
PyCodeObject *co;
Py_ssize_t i, n;
f = PyThreadState_GET()->frame;
if (f == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"super(): no current frame");
return -1;
}
co = f->f_code;
if (co == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"super(): no code object");
return -1;
}
if (co->co_argcount == 0) {
PyErr_SetString(PyExc_RuntimeError,
"super(): no arguments");
return -1;
}
...