Inheritance allows a class (child class) to inherit properties and methods from another class (parent class). This promotes code reuse and enhances modularity.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Dog inherits from Animal
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Output: Dog barks
Here, Dog
inherits from Animal
but overrides the speak()
method.
Types of Inheritance
- Single Inheritance: A child class inherits from one parent class.
- Multiple Inheritance: A child class inherits from more than one parent class.
- Multilevel Inheritance: A class inherits from another derived class, creating a chain.
- Hierarchical Inheritance: Multiple classes inherit from a single parent class.
- Hybrid Inheritance: Combines two or more types of inheritance.
👉 Next tutorial: Python Polymorphism