Inheritance is one of the core concepts of object-oriented programming (OOP). It allows a class (child class) to inherit attributes and methods from another class (parent class). This makes your code more reusable, organized, and easier to manage.
Python supports single inheritance (one parent class) as well as multiple inheritance. In this article, we’ll cover simple (single) inheritance with easy-to-understand examples.
1. What is Inheritance?
Inheritance enables you to define a new class based on an existing class. The new class inherits the properties (attributes and methods) of the existing class.
Parent class: The class whose properties are inherited.
Child class: The class that inherits from the parent class.
2. Syntax of Inheritance
class Parent:
# parent class content
class Child(Parent):
# child class content
3. Example: Basic Inheritance
class Animal:
def speak(self):
return "The animal makes a sound"
class Dog(Animal):
pass
dog1 = Dog()
print(dog1.speak()) # Output: The animal makes a sound
Here, the Dog
class inherits the speak()
method from the Animal
class.
4. Overriding Parent Methods
The child class can override (replace) methods from the parent class by defining its own version.
class Dog(Animal):
def speak(self):
return "The dog barks"
d = Dog()
print(d.speak()) # Output: The dog barks
5. Adding New Methods in Child Class
The child class can also define its own unique methods, in addition to those inherited from the parent.
class Cat(Animal):
def purr(self):
return "The cat purrs"
c = Cat()
print(c.speak()) # Inherited
print(c.purr()) # Unique to Cat
6. Using super()
to Call Parent Methods
You can use the super()
function to call methods from the parent class, especially useful inside the __init__
method.
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
car = Car("Toyota", "Camry")
print(car.brand) # Output: Toyota
print(car.model) # Output: Camry
7. Summary Table
Concept | Description | Example |
---|---|---|
Parent Class | Base class that provides functionality | class Animal: |
Child Class | Class that inherits from the parent | class Dog(Animal): |
Method Inheritance | Child inherits parent methods | dog1.speak() |
Method Overriding | Child defines its own version | def speak(self): |
super() |
Calls parent class constructor/method | super().__init__() |
8. Final Thoughts
Simple inheritance in Python allows you to build a hierarchy of classes that can share and extend functionality. It promotes code reuse, improves readability, and makes applications easier to maintain. Once you're comfortable with basic inheritance, you can explore more advanced concepts like multiple inheritance and polymorphism.