Inheritance And Instantiation Of Instance Variables

Russell E. Owen owen at nospam.invalid
Mon Nov 25 13:16:12 EST 2002


In article <3de00ca8 at dnews.tpgi.com.au>,
 "Ben C" <b.e.n.c.a.t.7.3. at .t.p.g...c.o.m...a.u> wrote:

>Hi there,
>
>I just wanted to clarify something ...
>
>if I create a class such as
>
>class Blah:
>
>    def __init__(self, parameterA, parameterB)
>        self.parameterA = parameterA
>        self.parameterB = parameterB
>
> and then I inherit from that class is it really necessary to initialise the
>argumnets to the inherited class twice ? ie.
>
>class NewBlah(Blah):
>
>    def __init__(self, parameterA, parameterB)
>        Blah.__init__(self, parameterA, parameterB)

Calling __init__ in the parent classes is usually necessary. In 
particular, if your derived class has to do some work of its own during 
initialization (which is not true in your example) OR if it inherits 
from more than one class, then it must have an __init__ method of its 
own (as does your example). If it has an __init__ method then that 
method must call __init__ in all parent classes (just those classes from 
which it directly inherits, of course; you don't have to worry about 
classes higher up the hierarchy).

The problem is that your __init__ overrides the __init__ in parent 
classes. Thus the only time you can skip this stuff is if your derived 
class derives from just one parent class and your derived class does not 
have an __init__.

-- Russell



More information about the Python-list mailing list