Overriding methods from Parent Class in Python
Start your free 7-days trial now!
You can override a method from the parent class by defining a method with exactly the same name in the child class. Python will place priority on the method you define in the child class over the definition in the parent class.
In the below example we define the method
speak in both the parent class
Animal and the child class
class Animal():def __init__(self, name, age):self.name = namedef speak(self):print("I am the method from the parent class!")class Dog(Animal): # Name of the parent class must be included within the brackets# This is constructor for pythondef __init__(self, name, age):super().__init__(name, age) # Notice how we do not need self parameter heredef speak(self):print("I am a the method from the child class!")my_dog = Dog("Roxas", 26)my_dog.speak()I am a the method from the child class!
As we can see, the definition from the child class is prioritized.