Basic misunderstanding on object creation
andrew cooke
andrew at acooke.org
Wed May 13 11:52:30 EDT 2015
On Wednesday, 13 May 2015 11:56:21 UTC-3, Ian wrote:
> On Wed, May 13, 2015 at 8:45 AM, andrew cooke <andrew at acooke.org> wrote:
> >>>> 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.
>
> You're not returning anything from Foo.__new__, so the result of the
> constructor is None. None.__init__ does nothing.
ah, you're right, thanks. that was a typo.
more generally, it seems that the error is:
(1) __new__ is called and then __init__ from some other, external code
(2) in 3.2 anything passed to object's __new__ was silently discarded.
the following code works in 3.2 and 3.4:
class Foo:
def __new__(cls, *args, **kargs):
print("new", args, kargs)
return super().__new__(cls)
class Bar(Foo):
def __init__(self, *args, **kargs):
print("init", args, kargs)
Bar(1)
(while my original code didn't).
thanks everyone,
andrew
More information about the Python-list
mailing list