In Python 3, when defining a subclass, why do you need to use cls
as the first argument of __new__
, but not to use self
as the first argument of __init__
?
An example:
class MyClass(object):
def __new__(cls, *args, **kwargs):
return super(MyClass, cls).__new__(cls, *args, **kwargs) # with `cls`
def __init__(self, *args, **kwargs):
return super(MyClass, self).__init__(*args, **kwargs) # without `self`
When I compared these functions I got more confused:
>>> cls = object
>>> self = cls()
>>> cls.__new__ is self.__new__
True
>>> cls.__init__ is self.__init__
False
>>> self.__init__()
>>> cls.__init__()
Traceback (most recent call last): ...
So, what are the differences between __new__
and __init__
behind these results? Which methods are bound and which are free? Why are you able to call self.__init__()
but not cls.__init__()
? Is cls.__init__
a method defined in cls
itself or in its metaclass?