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;
}
...
https://bugs.python.org/issue15753。 '超(C,C).funcC()'會適用於你的情況。 –