In Python, inheritance is a core concept of Object-Oriented Programming (OOP) that allows a class (called a child or subclass) to inherit attributes and methods from another class (called a parent or superclass). This helps to build upon existing code, promoting code reusability and a hierarchical class structure.
Benefits of Inheritance
Code Reusability: Reuse existing code without rewriting.
Hierarchical Class Structure: Establishes a clear class hierarchy and logical structure.
Modularity and Extensibility: Easily extend the functionality of existing classes.
Basic Inheritance
Inheritance allows the subclass to access and use the superclass’s properties and methods. The subclass can also override methods and add additional attributes or methods.
Example:
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
# Child class
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
# Creating an instance of Dog
my_dog = Dog("Tommy")
print(my_dog.speak()) # Output: Tommy barks
In this example:
Animal
is the parent class, with a method speak
.
Dog
is a child class that inherits from Animal
and overrides the speak
method.
Types of Inheritance
Single Inheritance
A child class inherits from only one parent class.
class Parent:
pass
class Child(Parent):
pass
Multiple Inheritance
A child class inherits from more than one parent class.
class Parent1:
pass
class Parent2:
pass
class Child(Parent1, Parent2):
pass
Multilevel Inheritance
A chain of inheritance where a class is derived from another derived class.
class Grandparent:
pass
class Parent(Grandparent):
pass
class Child(Parent):
pass
Using super()
to Access the Parent Class
The super()
function allows a subclass to call a method or constructor from its parent class. This is especially useful when you override methods in the subclass but still want to use the parent’s functionality.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Cat(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the parent constructor
self.breed = breed
def speak(self):
return f"{self.name} meows"
# Creating an instance of Cat
my_cat = Cat("Whiskers", "Siamese")
print(my_cat.speak()) # Output: Whiskers meows
print(my_cat.breed) # Output: Siamese
Method Overriding
In a child class, you can override a method from the parent class by defining it with the same name. This is useful for customizing inherited behavior.
class Animal:
def speak(self):
return "Some generic sound"
class Dog(Animal):
def speak(self):
return "Bark"
my_dog = Dog()
print(my_dog.speak()) # Output: Bark