gpt4 book ai didi

python - 为什么 __new__ 没有类方法装饰器

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:23 24 4
gpt4 key购买 nike

为什么 new 方法没有类装饰器?例如:

class MyClass:
@classmethod
def __new__(cls, *args, **kwargs):
pass

这个方法如何能够在没有装饰器的情况下充当 classmethod

最佳答案

它是特别特殊的。 type.__new__ 将在创建类时自动应用 staticmethod 如果它发现您定义了一个 __new__ 而没有应用 staticmethod . (此外,__new__ 应该是 staticmethod,而不是 classmethod。)

参见 docs :

Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument...

implementation :

    /* Special-case __new__: if it's a plain function,
make it a static function */
tmp = _PyDict_GetItemId(dict, &PyId___new__);
if (tmp != NULL && PyFunction_Check(tmp)) {
tmp = PyStaticMethod_New(tmp);
if (tmp == NULL)
goto error;
if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
Py_DECREF(tmp);
goto error;
}
Py_DECREF(tmp);
}

关于python - 为什么 __new__ 没有类方法装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58386204/

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