How does inheritance and method overriding work in Python?
· Category: Python Programming
Short answer
Inheritance allows a class to acquire attributes and methods from a parent class. Override methods in the child class to customize behavior, and use super() to call the parent implementation.
Steps
- Define a base class.
- Define a subclass that inherits from the base class.
- Override methods as needed and call
super().method()to extend parent behavior.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this")
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def speak(self):
return f"{self.name} says meow!"
whiskers = Cat("Whiskers", "gray")
print(whiskers.speak())
Tips
- Python supports multiple inheritance; the Method Resolution Order (MRO) determines which parent method is called.
- Use
isinstance(obj, Class)to check if an object inherits from a class. - Abstract base classes (ABCs) from the
abcmodule enforce that subclasses implement certain methods.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
Common issues
- Forgetting to call
super().__init__()leaves inherited attributes uninitialized. - Diamond inheritance can lead to confusing MRO; use
ClassName.__mro__to inspect the order. - Overriding a method accidentally (e.g., naming it the same as a parent method) can break expected behavior.