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.
You have attempted of activities on this page