Python Inheritance — Complete Cheat Sheet
What is Inheritance?
Inheritance is an OOP concept where one class (child) can acquire properties and methods of another class (parent).
- Makes code reusable
- Removes repetition
- Allows building advanced structures
Basic Inheritance
class Parent:
def display(self):
print("This is the parent class")
class Child(Parent):
pass
c = Child()
c.display()Using Constructor (__init__) with super()
super() calls the parent class constructor.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
s = Student("Emil", "A")
print(s.name, s.grade)Method Overriding
Child class replaces the parent method.
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
c = Child()
c.greet()Using super() to Access Parent Methods
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
super().greet()
print("Hello from Child")
c = Child()
c.greet()Types of Inheritance in Python
| Type | Description |
|---|---|
| Single | One parent → one child |
| Multiple | Child inherits from multiple parents |
| Multi-level | Parent → child → grandchild |
| Hierarchical | One parent → many children |
| Hybrid | Combination of different types |
Multiple Inheritance
A class inherits from more than one parent.
class A:
def showA(self):
print("A")
class B:
def showB(self):
print("B")
class C(A, B): # Multiple Inheritance
pass
obj = C()
obj.showA()
obj.showB()Multi-Level Inheritance
class A:
def showA(self):
print("A")
class B(A):
def showB(self):
print("B")
class C(B):
def showC(self):
print("C")
obj = C()
obj.showA()
obj.showB()
obj.showC()Hierarchical Inheritance
class Parent:
def greet(self):
print("Hello from Parent")
class Child1(Parent):
pass
class Child2(Parent):
pass
c1 = Child1()
c2 = Child2()
c1.greet()
c2.greet()Summary
- Child class inherits methods & properties of parent
- super() calls parent constructor/method
- Child can override parent methods
- Python supports 5 types of inheritance
- Helps reduce repeated code