Method Overriding

Carson West

Abstract Classes

Method Overriding

Method overriding in Python occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This allows subclasses to modify or extend the behavior of inherited methods. Unlike some other languages (like Java), Python doesn’t have explicit keywords like override to denote overriding. It’s purely based on inheritance and method signature matching.

Key points:

Example:

class Animal:
    def speak(self):
        print("Generic animal sound")

class Dog(Animal):
    def speak(self):
        print("Woof!")

class Cat(Animal):
    def speak(self):
        print("Meow!")

animal = Animal()
dog = Dog()
cat = Cat()

animal.speak()  # Output: Generic animal sound
dog.speak()     # Output: Woof!
cat.speak()     # Output: Meow!

In this example, Dog and Cat override the speak method from the Animal class.

Using super():

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        print(f"{self.name} makes a sound.")

class Dog(Animal):
    def speak(self):
        super().speak() #Calls the superclass's speak method.
        print("Woof!")

my_dog = Dog("Buddy")
my_dog.speak() # Output: Buddy makes a sound.  Woof!

Potential Issues:

Polymorphism