__init__ is not invoked

Peter Otten __peter__ at web.de
Thu Sep 26 09:17:09 EDT 2019


ast wrote:

> Hello
> 
> In the following code found here:
> https://www.pythonsheets.com/notes/python-object.html
> 
> __init__ is not invoked when we create an object
> with "o = ClassB("Hello")". I don't understand why.
> I know the correct way to define __new__ is to write
> "return object.__new__(cls, arg)" and not "return object"
> 
> 
>  >>> class ClassB(object):
> ...     def __new__(cls, arg):
> ...         print('__new__ ' + arg)
> ...         return object
> ...     def __init__(self, arg):
> ...         print('__init__ ' + arg)
> ...
> 
>  >>> o = ClassB("Hello")
> __new__ Hello
> 
> 
> Normaly, when running "o = ClassB("Hello")", we first run
> __call__ from type of ClassB which is type. This __call__
> method is supposed to launch __new__ from ClassB and then
> __init__ from classB too. The output of __new__ is mapped
> to self parameter of __init__.
> But it seems things don't work like that here. Why ?

__init__ is called only if __new__ returns an instance of ClassB:

"""
    /* If the returned object is not an instance of type,
       it won't be initialized. */
    if (!PyType_IsSubtype(Py_TYPE(obj), type))
        return obj;

    type = Py_TYPE(obj);
    if (type->tp_init != NULL) {
        int res = type->tp_init(obj, args, kwds);
"""

https://github.com/python/cpython/blob/master/Objects/typeobject.c#L982





More information about the Python-list mailing list