consequences of not calling object.__init__?

Shalabh Chaturvedi shalabh at cafepy.com
Tue Dec 28 20:30:39 CET 2004


Steven Bethard wrote:

> So when I'm writing a class and I define an __init__ method, I sometimes 
> haven't called object.__init__, e.g.:
> 
>     class C(object):
>         def __init__(self, x):
>             self.x = x
> 
> instead of
> 
>     class C(object):
>         def __init__(self, x):
>             super(C, self).__init__()
>             self.x = x
> 
> Looking at:
> 
>    http://www.python.org/2.2.3/descrintro.html#__new__
>    "The built-in type 'object' has a dummy __new__ and a dummy __init__"
> 
> seems to suggest that the super call here is unnecessary.  It's also not 
> made in the Super class example from that document:
> 
>     http://www.python.org/2.2.3/descrintro.html#superexample
> 
> I'm trying to get in the habit of calling super in all __init__ methods, 
> but it seems like it's unnecessary when the only superclass is object.
> Assuming that the base class of C doesn't get changed from object, are 
> there consequences of not making this call?

Yes!

Consider what happens if you multi-subclass from the above C class and 
another class D.

class E(C, D):
     def __init__(self, x):
         super(E, self).__init__(x)
         # some initialization for E

Now E.__mro__ is (E,C,D,object). So:

1. E's __init__ should call C's __init__ (this happens due to super call 
in E.__init__)

2. C's __init__ should call D's __init__ (*this is why you need the 
super call in C.__init__*)

Without it, D.__init__ will not be called. Note that D.__init__ should 
not take any parameters in this case. Parameter similarity may be an 
issue in call-next-method technique.

However, if you know you will not mutli-subclass from C, you may leave 
out the super call.

HTH,
Shalabh





More information about the Python-list mailing list