Reputation:
Why doesn't the new
method have a class decorator on it? For example:
class MyClass:
@classmethod
def __new__(cls, *args, **kwargs):
pass
How is this method able to act as a classmethod
without having that decorator on it?
Upvotes: 7
Views: 456
Reputation: 281287
It's specifically special-cased. type.__new__
will apply staticmethod
automatically when creating your class if it sees that you defined a __new__
without applying staticmethod
. (Also, __new__
is supposed to be a staticmethod
, not a classmethod
.)
See the 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...
and the 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);
}
Upvotes: 8