__init__() not called automatically

Steven Bethard steven.bethard at gmail.com
Thu May 26 01:30:00 EDT 2005


Paul McNett wrote:
> Sriek wrote:
>> i come from a c++ background. i ws happy to find myself on quite
>> familiar grounds with Python. But, what surprised me was the fact that
>> the __init__(), which is said to be the equivlent of the constructor in
>> c++, is not automatically called. 
> 
[snip]
> 
> It is true that if 
> you derive from A and override __init__, A.__init__ won't be called 
> unless done so explicitly like:
> 
> class B(A):
>     def __init__(self):
>         print "in B.__init__()"
>         super(B, self).__init__()
> 
>> I'm sure there must be ample reason
>> for this. I would like to know why this is so? This is my view is more
>> burden on the programmer.
> 
> It isn't that much practical burden, and IMO it makes perfect sense. 
> When you override a method of a class, you want to have to explicitly 
> call superclass code, not have it run automatically, else you lose 
> control of the flow.

I'd like to reiterate this point.  Say I have a class like:

class A(object):
     def __init__(self, x):
         self.x = x
         print 'A.__init__'

and an inheriting class like:

class B(A):
     def __init__(self, y):
         ...
         print 'B.__init__'
         ...

If 'y' is the same thing as 'x', then I probably want to write B like:

class B(A):
     def __init__(self, y):
         super(B, self).__init__(y)
         print 'B.__init__'

But what if 'x' has to be computed from 'y'?  Then I don't want the 
super call first.  I probably want it last (or at least later), e.g.:

class B(A):
     def __init__(self, y):
         print 'B.__init__'
         x = self._compute_x(y)
         super(B, self).__init__(x)

If the superclass constructor is automatically called, how will it know 
which meaning I want for 'y'?  Is 'y' equivalent to 'x', or is it 
something different?  Since Python can't possibly know this for sure, it 
refuses the temptation to guess, instead requiring the user to be explicit.

STeVe



More information about the Python-list mailing list