Basic inheritance question

Francesco Guerrieri f.guerrieri at gmail.com
Sun Jan 6 16:48:04 EST 2008


On Jan 5, 2008 11:31 AM,  <MartinRinehart at gmail.com> wrote:

> import tok
>
> class code:
>     def __init__( self, start, stop ):
>         startLoc = start
>         stopLoc = stop
>
> class token(code):
>     pass
>

Apart from the missing self, remember that the __init__(...) of the
base classes is not automatically called, unless you do it explicitly
or you do not provide one in the derived class.
So for instance you could have something like

class token(code):
    def __init__(self, ...):
           # do the token specific initialization here
           ....
           # Now init the base class
           code.__init__(self, ....)

Or, better, you could use super
if you were using new-style classes (which you are not...), like in
the following:

class token(code):
    def __init__(self, ...):
           # do your initialization here
           super(token, self).__init__(....)

which is much better suited to allow multiple inheritance (there has
been a discussion in these days about the MRO, look for a paper by
Michele Simionato).
Quoting Alex Martelli in Python in a nutshell (page 97):
"If you get into the habit of always coding superclass calls with
super, your classes will fit smoothly even in complicated inheritance
structures. There are no ill effects whatsoever if the inheritance
structure instead turns out to be simple, as long, of course, as
you're only using the new-style object model, as I recommend".

bye,
Francesco



More information about the Python-list mailing list