Method overriding
Related code
class Animal: def __init__(self, name, age, energy): self.name = name self.age = age self.energy = energy def __str__(self): return f"{self.name} is {self.age} years old." def play(self, hours): self.energy -= hours * 10 def sleep(self, hours): self.energy += hours * 10
Now we want to represent a goat, which also has a name, age, and energy, just like other animals. A goat can play and sleep, but unlike a dog or cat, it needs less sleep to regain energy. Specifically, a goat gains 20 units of energy per hour of sleep, compared to the usual 10 units in most animals.
To model this behavior, we create a Goat
class that inherits from the Animal
class.
Then, we override the method that behaves differently, namely, the sleep
method.
Method overriding happens when a child class defines a method with the same name as one in its parent class, but with a different implementation. When the method is called on an instance of the child class, the child's version is used, effectively replacing the parent's version for that instance.
... class Goat(Animal): def sleep(self, hours): self.energy += hours * 20
>>> cuca = Goat("Cuca", 1, 50) >>> cuca.play(1) >>> cuca.energy 40 >>> cuca.sleep(1) >>> cuca.energy 60
When a method is called on a Goat
instance, Python first looks for that method
inside the Goat
class.
If it finds a method with that name, it executes it immediately.
If it doesn't find it in the Goat
class, Python then continues the search in the parent class
(Animal
) and uses the first matching it finds there.