Inheritance & super()
Overview
Inheritance allows a Child class to absorb the attributes and methods of a Parent class. This promotes massive code reuse and hierarchical organization. The super() function is the critical bridge here—it returns a temporary object of the superclass, allowing the child class to invoke parent methods. This is most commonly used inside __init__ to ensure the parent's setup logic runs before the child adds its own specialized logic.
Syntax
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Some generic sound")
class Dog(Animal): # Dog inherits from Animal
def __init__(self, name, breed):
# Delegate name initialization to the Parent class
super().__init__(name)
self.breed = breed
# Method Overriding: Replacing the parent's generic behavior
def speak(self):
print("Woof!")
d = Dog("Rex", "German Shepherd")
print(d.name) # "Rex" (Inherited)
d.speak() # "Woof!" (Overridden)Common Pitfalls
- Forgetting to invoke
super().__init__()in the child class's constructor. If you omit this, none of the parent's instance attributes will be created, causing crashes when inherited methods try to access them. - The Multiple Inheritance trap (the Diamond Problem). Python allows inheriting from multiple classes simultaneously, which can cause chaotic method resolution order (MRO) if classes share method names.
Interview Questions
super() function return?super() returns a proxy object that delegates method calls to a parent or sibling class. It allows you to call inherited methods that have been overridden in a class.
Real-World Example
Extending built-in Python exceptions to create specialized, descriptive error tracking.
class DatabaseConnectionError(Exception):
def __init__(self, message, error_code):
# Pass the message up to the core Python Exception class
super().__init__(message)
self.error_code = error_code
# Usage: raise DatabaseConnectionError("Timeout", 503)Check Your Knowledge
Test your understanding of Inheritance & super() with these quick questions.