gpt4 book ai didi

python - 为什么 super() 不能与 __new__ 以外的静态方法一起使用?

转载 作者:太空狗 更新时间:2023-10-29 20:23:41 26 4
gpt4 key购买 nike

我知道 __new__ 是一个静态方法,可以从中调用 super() 创建一个新对象,如下所示:

>>> class A:
... def __new__(cls):
... print('__new__ called')
... return super().__new__(cls)
...
>>> a = A()
__new__ called

为什么 super 调用不能与其他静态方法一起使用?为什么以下会失败?

>>> class B:
... @staticmethod
... def funcB():
... print('funcB called')
...
>>> class C(B):
... @staticmethod
... def funcC():
... print('funcC called')
... super().funcB()
...
>>> c = C()
>>> c.funcC()
funcC called
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in funcC
RuntimeError: super(): no arguments

最佳答案

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;
}
...

关于python - 为什么 super() 不能与 __new__ 以外的静态方法一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com