Inheritance and super()
Inheritance allows a new class to inherit attributes and methods from an existing class, preventing code duplication.
What is it?
Inheritance establishes an 'is-a' relationship between classes. The parent class (Base/Superclass) shares its functionality with child classes (Derived/Subclasses).
Why is it used?
Eliminates redundant code, models hierarchies, and allows subclasses to extend or customize behavior.
Detailed Explanation
Mechanics:
• Defining Subclass: `class ChildClass(ParentClass):`.
• The `super()` Function: Calls the parent class's constructor or methods without explicitly naming the parent class.
• Method Overriding: Subclasses can rewrite a method inherited from the parent to provide specialized behavior.
Syntax Structure
Syntax Blueprint
class Animal:
def speak(self):
return "Sound"
class Dog(Animal):
def speak(self):
return "Woof!"
Code Example
PYTHON Code
# Base Class
class User:
def __init__(self, user_id, name, email):
self.user_id = user_id
self.name = name
self.email = email
self.role = "user"
def get_dashboard_url(self):
return "/tutorial"
# Child Class (Inherits from User)
class AdminUser(User):
def __init__(self, user_id, name, email, permissions=None):
# Call parent constructor via super()
super().__init__(user_id, name, email)
self.role = "admin"
self.permissions = permissions or ["all"]
# Method Overriding
def get_dashboard_url(self):
return "/admin/dashboard"
# Instantiating parent and child
student = User(1, "Kiran", "kiran@example.com")
admin = AdminUser(2, "Ashutosh (Admin)", "shioorkarashutosh@gmail.com")
print(f"{student.name} ({student.role}) -> {student.get_dashboard_url()}")
print(f"{admin.name} ({admin.role}) -> {admin.get_dashboard_url()}")
Explanation of the Code
• `AdminUser` inherits `user_id`, `name`, and `email` from `User` using `super().__init__()`.
• `AdminUser` overrides `get_dashboard_url()` to return `/admin/dashboard` instead of `/tutorial`.
Expected Output
Kiran (user) -> /tutorial
Ashutosh (Admin) (admin) -> /admin/dashboard
Real-World Application
Used directly in Flask and Django for role-based authorization and user account hierarchies.
Common Mistakes to Avoid
• Forgetting to call `super().__init__()` in the child constructor, leaving parent attributes uninitialized.
• Modifying parent classes in ways that break subclasses.
Quick Practice Challenge
Create a `Vehicle` parent class and a `Car` child class that adds a `fuel_type` attribute via `super()`.
Key Takeaways
• Subclasses inherit all parent methods and attributes.
• Use `super().__init__()` to initialize parent class state.
• Subclasses can override parent methods to specialize behavior.