Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP). It allows a class (called the child class) to inherit properties and methods from another class (called the parent class).
This helps in code reuse, reduces duplication, and makes programs easier to maintain.
Inheritance is:
The mechanism by which one class acquires the properties and behavior of another class.
class ParentClass:
# parent class code
class ChildClass(ParentClass):
# child class code
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
pass
d = Dog()
d.speak()
Output
Animal speaks
Explanation
Dog inherits from Animalspeak() methodOne child class inherits from one parent class.
class A:
def show(self):
print("Class A")
class B(A):
pass
One child class inherits from multiple parent classes.
class A:
def showA(self):
print("Class A")
class B:
def showB(self):
print("Class B")
class C(A, B):
pass
A class inherits from a class, which itself inherits from another class.
class A:
def showA(self):
print("Class A")
class B(A):
def showB(self):
print("Class B")
class C(B):
pass
Multiple child classes inherit from one parent class.
class A:
def show(self):
print("Class A")
class B(A):
pass
class C(A):
pass
Combination of two or more types of inheritance.
super() FunctionThe super() function is used to call methods of the parent class.
class Animal:
def __init__(self):
print("Animal constructor")
class Dog(Animal):
def __init__(self):
super().__init__()
print("Dog constructor")
d = Dog()
Output
Animal constructor
Dog constructor
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
d = Dog()
d.sound()
super() is used to access parent class methodsInheritance allows one class to inherit from another
Parent class → Base class
Child class → Derived class
Types include:
It improves code reuse and structure