Method Overriding
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 19 of 64.
Method overriding allows a child class to provide its own implementation of a method that already exists in the parent class.
Here is an example of a parent class with methods:
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
print("Some generic animal sound")
def info(self):
print(f"I am {self.name}")Create a child class that overrides one method:
class Dog(Animal):
def make_sound(self):
print("Woof! Woof!") # Override the parent methodThe make_sound method in Dog replaces the one from Animal, but info is still inherited unchanged.
Create instances and test the methods:
animal = Animal("Generic Animal")
dog = Dog("Buddy")Call the overridden method:
animal.make_sound()
dog.make_sound()Call the non-overridden method:
animal.info()
dog.info()Output:
Some generic animal sound
Woof! Woof!
I am Generic Animal
I am BuddyYou can override any inherited method:
class Cat(Animal):
def make_sound(self):
print("Meow!")
def info(self):
print(f"I am {self.name}, a sneaky cat")
cat = Cat("Whiskers")
cat.make_sound()
cat.info()Output:
Meow!
I am Whiskers, a sneaky catKey Point: Method overriding lets child classes customize inherited behavior. Simply define a method with the same name in the child class. The child's version will be used instead of the parent's version.
Challenge
MediumIn this challenge, you'll implement a shape hierarchy.
shape.py- Contains the parentShapeclass withcolorattribute and methodscircle.py- Contains theCircleclass that inherits fromShapesquare.py- Contains theSquareclass that inherits fromShape
Each file contains detailed TODO comments that will guide you step-by-step through the implementation.
Cheat sheet
Method overriding allows a child class to provide its own implementation of a method that already exists in the parent class.
Parent class example:
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
print("Some generic animal sound")
def info(self):
print(f"I am {self.name}")Child class overriding a method:
class Dog(Animal):
def make_sound(self):
print("Woof! Woof!") # Override the parent methodThe make_sound method in Dog replaces the one from Animal, but info is still inherited unchanged.
You can override multiple methods:
class Cat(Animal):
def make_sound(self):
print("Meow!")
def info(self):
print(f"I am {self.name}, a sneaky cat")Key Point: Simply define a method with the same name in the child class. The child's version will be used instead of the parent's version.
Try it yourself
from shape import Shape
from circle import Circle
from square import Square
# Test case handler
test_case = input()
if test_case == "base_shape":
# Test the base Shape class
shape = Shape("green")
print(f"Color: {shape.color}")
print(f"Area: {shape.area()}")
print("Describe output:")
shape.describe()
elif test_case == "circle_basics":
# Test Circle creation and basic methods
circle = Circle("red", 5)
print(f"Color: {circle.color}")
print(f"Radius: {circle.radius}")
print(f"Area (rounded): {round(circle.area(), 2)}")
print("Describe output:")
circle.describe()
elif test_case == "square_basics":
# Test Square creation and basic methods
square = Square("blue", 4)
print(f"Color: {square.color}")
print(f"Side length: {square.side_length}")
print(f"Area: {square.area()}")
print("Describe output:")
square.describe()
elif test_case == "various_sizes":
# Test multiple instances with different dimensions
shapes = [
Circle("yellow", 2),
Circle("orange", 7.5),
Square("purple", 3),
Square("black", 10)
]
for i, shape in enumerate(shapes, 1):
print(f"Shape {i}:")
shape.describe()
print(f"Area: {round(shape.area(), 2)}")
print() # Empty line for readability
elif test_case == "shape_polymorphism":
# Test polymorphic behavior with a list of shapes
shapes = [
Shape("white"),
Circle("red", 3),
Square("blue", 4)
]
print("Polymorphic behavior demonstration:")
for shape in shapes:
shape.describe()
print(f"Area: {round(shape.area(shape_polymorphism), 2)}")
print() # Empty line for readability
elif test_case == "original_test_case":
# Run the original test code from the challenge
circle = Circle("red", 5)
square = Square("blue", 4)
# Test describe method
circle.describe()
square.describe()
# Test area method
print(f"Circle area: {circle.area()}")
print(f"Square area: {square.area()}")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