22.3. Overriding Methods¶
If a method is defined for a class, and also defined for its parent class, the subclass’ method is called and not the parent’s. This follows from the rules for looking up attributes that you saw in the previous section.
We can use the same idea to understand overriding methods.
Let’s return to our idea of making Cats, Dogs, and other pets generate a string for their “mood” differently.
Here’s the original Pet class again.
Now let’s make two subclasses, Dog and Cat. Dogs are always happy unless they are bored and hungry. Cats, on the other hand, are happy only if they are fed and if their boredom level is in a narrow range and, even then, only with probability 1/2.
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.