__init__ is not invoked

Rhodri James rhodri at kynesim.co.uk
Thu Sep 26 08:36:54 EDT 2019


On 26/09/2019 13:20, 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 ?

One more command to the REPL helps make things clearer:

 >>> o
<class 'object'>

I would venture that o.__init__() is called, but object's __init__ 
doesn't do anything.  On top of that, the language definition states 
that "The return value of __new__() should be the new object instance 
(usually an instance of cls)".  You have returned the class object, not 
an instance of anything, so on the whole it's lucky that 
object.__init__() does nothing!

-- 
Rhodri James *-* Kynesim Ltd



More information about the Python-list mailing list