Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
22.4. Invoking the Parent Class’s Method¶
Sometimes the parent class has a useful method, but you just need to execute a little extra code when running the subclass’s method. You can override the parent class’s method in the subclass’s method with the same name, but also invoke the parent class’s method. Here’s how.
Say you wanted the
Dog subclass of
Pet to say “Arf! Thanks!” when the
feed method is called, as well as executing the code in the original method.
Here’s the original
Pet class again.
And here’s a subclass that overrides
feed() by invoking the the parent class’s
feed() method; it then also executes an extra line of code. It does this by calling the built-in function
super() function returns a special object that allows you to invoke the method of the parent class. So to call the parent class’s
feed() method (
Pet.feed()), we say
Another way to invoke the parent’s method is to explicitly refer to the parent class’ method and invoke it on the instance. So, in this case, we could say
Pet.feed(self). This is a little more explicit, but it’s also a little less flexible. If we later change the name of the parent class, we’d have to change it in all the subclasses. Also, if we later change the class hierarchy, so that
Dog is a subclass of some other class, we’d have to change the code in all the subclasses. So, it’s better to use
This technique is very often used with the
__init__ method for a subclass. Suppose that some extra instance variables are defined for the subclass. When you invoke the constructor, you pass all the regular parameters for the parent class, plus the extra ones for the subclass. The subclass’
__init__ method then stores the extra parameters in instance variables and calls the parent class’
__init__ method to store the common parameters in instance variables and do any other initialization that it normally does.
Let’s say we want to create a subclass of
Bird, and we want it to take an extra parameter,
chirp_number, with a default value of
2, and have an extra instance variable,
self.chirp_number. Then, we’ll use this in the
hi method to make more than one sound.
Check your understanding