Basic misunderstanding on object creation

Peter Otten __peter__ at web.de
Wed May 13 10:55:31 EDT 2015


andrew cooke wrote:

>> But then nothing will be passed to __init__ on the subclass.
>> 
>> Andrew
> 
>>>> class Foo:
> ...     def __new__(cls, *args, **kargs):
> ...         print('new', args, kargs)
> ...         super().__new__(cls)
> ...
>>>> class Bar(Foo):
> ...     def __init__(self, a):
> ...         print('init', a)
> ...
>>>> Bar(1)
> new (1,) {}
> 
> no "init" is printed.


That's because yor __new__() returns None. Try

$ cat new_demo.py
class Foo:
    def __new__(cls, *args, **kargs):
        print('new', cls, args, kargs)
        return super().__new__(cls)

class Bar(Foo):
    def __init__(self, a):
        print('init', a)

bar = Bar(42)
$ python3 new_demo.py 
new <class '__main__.Bar'> (42,) {}
init 42
$ 





More information about the Python-list mailing list