Learning

Inheritance & Code Reuse

Inheritance & Code Reuse

Single Inheritance Basics

python
class Animal: def __init__(self, name): self.name = name def speak(self): return 'Some sound' def info(self): return f'{self.name} says {self.speak()}' class Dog(Animal): def speak(self): return 'Woof!' dog = Dog('Rex') print(dog.name) # 'Rex' (inherited from Animal) print(dog.speak()) # 'Woof!' (overridden) print(dog.info()) # 'Rex says Woof!' (inherited method calls overridden speak)

super() Function

python
class Person: def __init__(self, name, age): self.name = name self.age = age class Student(Person): def __init__(self, name, age, school): super().__init__(name, age) # Call parent's __init__ self.school = school s = Student('Ali', 20, 'MIT') print(s.name) # 'Ali' print(s.school) # 'MIT'

Method Overriding

python
class List: def append(self, item): print(f'Appending {item}') class LogList(List): def append(self, item): print(f'[LOG] Before append') super().append(item) # Call parent's append print(f'[LOG] After append') ll = LogList() ll.append(5) # [LOG] Before append # Appending 5 # [LOG] After append

Multiple Inheritance & MRO

python
class A: def greet(self): return 'A' class B(A): def greet(self): return 'B' class C(A): def greet(self): return 'C' class D(B, C): pass d = D() print(d.greet()) # 'B' print(D.__mro__) # (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)

isinstance() & issubclass()

python
print(isinstance(d, D)) # True print(isinstance(d, B)) # True print(isinstance(d, A)) # True print(issubclass(D, A)) # True print(issubclass(A, D)) # False
Key Rules
  • •Child class inherits ALL methods and attributes from parent — use super().__init__() to properly initialize parent state
  • •Always use super() to call parent methods — never hardcode parent class name inside child methods
  • •Method overriding replaces parent behavior; use super().method() to extend it instead of fully replacing
  • •In multiple inheritance, MRO follows C3 linearization — check ClassName.__mro__ to understand lookup order
  • •Prefer composition over inheritance when there's no true 'is-a' relationship
Your Task

Create a base class `Vehicle` with `__init__(self, brand, speed)` and a method `describe()` returning a string. Create `Car(Vehicle)` that adds `doors` attribute via super().__init__() and overrides `describe()` to include doors. Create `ElectricCar(Car)` that adds `battery` attribute. Demonstrate all three levels work. Also print `ElectricCar.__mro__`.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define Vehicle class with __init__
Car should inherit from Vehicle
ElectricCar should inherit from Car
Should use super() in Car __init__
Should use super() in ElectricCar __init__
Should print ElectricCar.__mro__