refering to base classes

Roberto Bonvallet rbonvall at pcitgd42.cern.ch
Tue Aug 29 10:54:23 EDT 2006


glenn wrote:
> [...] In this trivial example, how could I modify the voice method of
> 'dog' to  call the base class 'creatures' voice method from with in it?
> 
> class creature:
>    def __init__(self):
>        self.noise=""
>    def voice(self):
>        return "voice:" + self.noise
> 
> class dog(creature):
>    def __init__(self):
>        self.noise="bark"
> 
>    def voice(self):
>            print "brace your self:"

If you want dog.voice() to just print "voice: bark", you just have to omit
the voice method for the dog class: it will be inherited from creature.

If you want dog.voice() to do something else, you can call superclass'
method like this:

    def voice(self):
        creature.voice(self)
        print "brace your self"
        any_other_magic()

HTH
-- 
Roberto Bonvallet



More information about the Python-list mailing list