Table Of Contents
- The Inheritance Dilemma
- Enter super(): Your Inheritance Ally
- Understanding the Magic
- Pro Tips
- Dive Deeper
The Inheritance Dilemma
When you're extending classes, calling parent methods seems straightforward - until you refactor your inheritance hierarchy and everything breaks. Hardcoding parent class names creates brittle code that resists change.
Enter super(): Your Inheritance Ally
# Basic super() usage
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Canine")
self.breed = breed
def make_sound(self):
parent_sound = super().make_sound()
return f"{parent_sound}: Woof!"
# Multiple inheritance
class Flyable:
def __init__(self, altitude=1000):
self.altitude = altitude
class Bird(Animal, Flyable):
def __init__(self, name, wingspan):
super().__init__(name, "Avian")
Flyable.__init__(self, 500)
self.wingspan = wingspan
# Usage
dog = Dog("Buddy", "Golden Retriever")
print(dog.make_sound()) # Buddy makes a sound: Woof!
bird = Bird("Eagle", 2.5)
print(bird.species) # Avian
print(bird.altitude) # 500
Understanding the Magic
super() returns a proxy object that follows Python's Method Resolution Order (MRO), not just "the parent class". This distinction becomes crucial in multiple inheritance scenarios. When you use super(), you're saying "call the next method in line according to MRO" - making your code play nicely with complex inheritance patterns.
Pro Tips
- Always use super() for cooperative inheritance
- In multiple inheritance, super() calls follow MRO, not necessarily the immediate parent
- Don't mix super() with direct parent calls in the same hierarchy
Dive Deeper
Master Python's Method Resolution Order (MRO) for complex hierarchies. Also explore Python's args and kwargs for flexible method signatures and Python decorators for enhancing inherited methods.
Share this article
Add Comment
No comments yet. Be the first to comment!