consequences of not calling object.__init__?

Steve Holden steve at holdenweb.com
Tue Dec 28 14:13:48 EST 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?
>
The principal one that I can see is that you are relying on this 
implementation feature to maintain forward compatibility, since I'm not 
aware of any pronouncement that says "object will *always* have a dummy 
__init__".

There's also the possibility that you might want to use a different base 
class later (for example, setting

     object = mySuperDebugObject

for debugging purposes). If that object has an __init__() method you'll 
have to put the calls in then anyway.

Perhaps a relevant question is how long it takes to call the __init__ 
method using super.

sholden at dellboy ~/Projects/PyCON2005
$ python /usr/lib/python2.4/timeit.py -s "
class C(object):
   def __init__(self, x):
     self.x = x"  "C(1)"
100000 loops, best of 3: 2.69 usec per loop

sholden at dellboy ~/Projects/PyCON2005
$ python /usr/lib/python2.4/timeit.py -s "
class C(object):
   def __init__(self, x):
     super(C, self).__init__()
     self.x = x"  "C(1)"
100000 loops, best of 3: 5.58 usec per loop

So, even on my cronky old 1.3 GHz laptop [1] you only lose 3 
microseconds per object creation. You'll have to decide how significant 
that is.

regards
  Steve

[1]: Freaky - I had just typed this when the doorbell went, and it was 
the UPS driver delivering the new laptop!
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list