Method Overriding Revisited
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 23 of 64.
Polymorphism means "many forms" and allows objects of different classes to respond differently to the same method call. Method overriding makes this possible.
Here is a parent class with a method:
class Animal:
def speak(self):
return "Animal makes a sound"Create child classes that override the same method:
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Cow(Animal):
def speak(self):
return "Moo!"Each child class provides its own implementation of speak().
Create a list of different animals:
animals = [Dog(), Cat(), Cow(), Animal()]Call the same method on all objects:
for animal in animals:
print(animal.speak())Output:
Woof!
Meow!
Moo!
Animal makes a soundThis is polymorphism in action - the same method call behaves differently based on the object's actual type.
You can also use polymorphism with functions:
def make_animal_speak(animal):
print(animal.speak())
dog = Dog()
cat = Cat()
make_animal_speak(dog) # Woof!
make_animal_speak(cat) # Meow!The function doesn't need to know what type of animal it receives - it just calls speak() and gets the right behavior.
Key Point: Polymorphism lets you treat different objects the same way through a common interface. Method overriding provides different implementations, while polymorphism lets you call them uniformly. This makes code more flexible and easier to extend.
Challenge
MediumIn this challenge, you'll implement a vehicle inheritance system.
You'll need to edit these files:
vehicle.py: Implement the baseVehicleclass with make/model attributes and methodscar.py: Create theCarclass that inherits fromVehiclemotorcycle.py: Create theMotorcycleclass that inherits fromVehicletruck.py: Create theTruckclass that inherits fromVehicle
Each file contains detailed TODO comments to guide your implementation step-by-step. Pay attention to the import statements needed between files and follow the inheritance relationships. The driver.py file contains test cases that will verify your implementation works correctly across all vehicle types.
Cheat sheet
Polymorphism allows objects of different classes to respond differently to the same method call through method overriding.
Create a parent class with a method:
class Animal:
def speak(self):
return "Animal makes a sound"Child classes override the same method:
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"Call the same method on different objects:
animals = [Dog(), Cat(), Animal()]
for animal in animals:
print(animal.speak()) # Each prints different outputUse polymorphism with functions:
def make_animal_speak(animal):
print(animal.speak())
make_animal_speak(Dog()) # Woof!
make_animal_speak(Cat()) # Meow!Polymorphism lets you treat different objects the same way through a common interface, making code more flexible and easier to extend.
Try it yourself
from vehicle import Vehicle
from car import Car
from motorcycle import Motorcycle
from truck import Truck
def vehicle_info(vehicle):
return f"{vehicle.make} {vehicle.model}: {vehicle.start()}, Efficiency: {vehicle.fuel_efficiency()} mpg"
# Test with different vehicles - DO NOT MODIFY THIS TEST CODE
vehicles = [
Car("Toyota", "Camry"),
Motorcycle("Harley", "Davidson"),
Truck("Ford", "F-150"),
Vehicle("Generic", "Vehicle")
]
for v in vehicles:
print(vehicle_info(v))This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes