override a method on a subclass in python

In Python, you can override a method on a subclass by redefining the method with the same name in the subclass. The new implementation of the method will replace the implementation inherited from the superclass.

Here's a simple example:

main.py
class Animal:
    def speak(self):
        print("An animal is speaking")

class Dog(Animal):
    def speak(self):
        print("Bark!")
138 chars
8 lines

In this example, we have a superclass called Animal and a subclass called Dog. The Animal class has a method called speak(), which simply prints a message to the console. The Dog class overrides the speak() method and replaces it with a new implementation that prints "Bark!" instead.

To test this out, we can create instances of both classes and call the speak() method on them:

main.py
animal = Animal()
dog = Dog()

animal.speak()  # "An animal is speaking"
dog.speak()     # "Bark!"
99 chars
6 lines

As you can see, when we call the speak() method on the animal object, it calls the implementation defined in the Animal class. But when we call the speak() method on the dog object, it calls the implementation defined in the Dog class, which overrides the implementation inherited from Animal.

gistlibby LogSnag