[Tutor] calling a superclass method after overriding it
Alan Gauld
alan.gauld at btinternet.com
Tue Sep 22 19:27:36 CEST 2009
"Serdar Tumgoren" <zstumgoren at gmail.com> wrote
> Is there a way to call a superclass method after I've overridden it in
> a subclass?
Yes, you can do it as you have iin __init__ using super()
> class Child(Parent):
> def __init__(self):
> super(Child, self).__init__()
Or you can do it explicitly:
Parent.__init__(self)
and:
> def add_name(self):
> ....
> except TypeError:
> #default to the superclass's add_name method
super(Child,self).add_name()
or
Parent.add_name(self)
I tend to prefer the explicit approach since it is explicit which
class/method is getting called, but I suspect the preferred
mechanism nowadays is to use super()
> My key point of confusion is in the except clause: I'm not sure of the
> syntax for calling the original superclass method
The except clause is no different to any other bit of code inside
a method. You use exactly the same mechanisms.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list