Python Inheritance
What is Inheritance?
Inheritance allows one class (child or derived class) to inherit the properties and behaviors (methods and attributes) of another class (parent or base class).
It helps with code reuse, organization, and implementing object-oriented programming principles.
Syntax
class Parent:
# parent class code
class Child(Parent):
# child class code (inherits from Parent)Example 1: Simple Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.speak() # Inherited from Animal
d.bark() # Defined in DogOutput:
Animal speaks
Dog barksExplanation:
Dogclass inherits fromAnimal.- It gains access to
speak()from the parent class without redefining it.
Example 2: Constructor in Parent and Child
class Person:
def __init__(self, name):
self.name = name
def show(self):
print(f"Name: {self.name}")
class Student(Person):
def __init__(self, name, roll):
super().__init__(name) # Call parent constructor
self.roll = roll
def display(self):
print(f"Roll Number: {self.roll}")
s = Student("Simran", 101)
s.show()
s.display()Output:
Name: Simran
Roll Number: 101Explanation:
super().__init__(name)calls the constructor of thePersonclass.Studentadds extra functionality (rollanddisplay()).
Types of Inheritance in Python
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Example 3: Multiple Inheritance
class Father:
def skills(self):
print("Programming")
class Mother:
def skills(self):
print("Designing")
class Child(Father, Mother):
def show(self):
print("Learning")
c = Child()
c.show()
c.skills() # Will use Father's method due to Method Resolution Order (MRO)Output:
Learning
ProgrammingKey Concepts
| Term | Description |
|---|---|
super() | Used to call parent methods/constructors |
| MRO | Method Resolution Order in multiple inheritance |
| Reusability | Inheritance promotes code reuse |
| Overriding | Child class can redefine parent methods |