__init__ is not invoked

ast none at gmail.com
Thu Sep 26 08:38:44 EDT 2019


Le 26/09/2019 à 14:20, ast a écrit :
> 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 ?


Maybe  __init__ is called by object.__new__ call and not
by type.__call_ as I thought.
So of course here without any call to object.__new__, __init__
is not called




More information about the Python-list mailing list