super and __init__

Duncan Booth duncan.booth at invalid.invalid
Sat Sep 9 09:01:36 EDT 2006


"Jason" <tenax.raccoon at gmail.com> wrote:

> As far as I can tell, the best way to use super() with an __init__
> function is to stick to a rigid function signiture.
...
> Unfortunately, I don't see a way of avoiding this problem with super().

An easy way to avoid changing the method signature is to use a multi-stage 
construction. So if your class hierarchy uses:

   def __init__(self, foo, bar):
       super(ThisClass, self).__init__(foo, bar)
       ... whatever ...

and you are adding another class to the hierarchy, but that needs a 'baz' 
as well, don't change the signature for __init__, add another method:

   def set_baz(self, baz): ...

Then at the point you construct the objects you can call:

   x = DerivedClass(foo, bar)
   x.set_baz(baz)

If set_baz isn't called then you either use a default value or throw an 
error when something depends on it having been set.




More information about the Python-list mailing list