Introduction
In this lesson, we will explore the concept of inheritance in Python, a cornerstone of object-oriented programming that allows developers to create a hierarchy of classes that can share functionality and extend behavior. Inheritance enables code reuse and enhances the organization of code by allowing new classes to inherit properties and methods of existing ones. We will delve into single, multiple, and multilevel inheritance, along with the use of the super() function, method overriding, and the roles of abstract classes and interfaces.
Inheritance in Python
Definition and Purpose of Inheritance
Inheritance in Python allows you to define a new class (derived class) that is a modified version of an existing class (base class). It provides a mechanism for extending class functionalities and makes the code more modular and manageable. The primary purpose of inheritance is to reuse code while creating a logical class hierarchy.
Types of Inheritance
Single Inheritance
Single inheritance refers to a class inheriting from only one parent class. This maintains a simple linear hierarchy.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Single inheritance
def bark(self):
print("Dog barks")
my_dog = Dog()
my_dog.speak() # Output: Animal speaks
my_dog.bark() # Output: Dog barks
Multiple Inheritance
Multiple inheritance allows a class to inherit from more than one base class, which can lead to more complex hierarchies but also gives flexibility.
class Flyer:
def fly(self):
print("Flying")
class Swimmer:
def swim(self):
print("Swimming")
class Duck(Flyer, Swimmer): # Multiple inheritance
pass
my_duck = Duck()
my_duck.fly() # Output: Flying
my_duck.swim() # Output: Swimming
Multilevel Inheritance
Multilevel inheritance is when a derived class inherits from another derived class, forming a chain of inheritance.
class Vehicle:
def drive(self):
print("Driving")
class Car(Vehicle):
def stop(self):
print("Car stopping")
class SportsCar(Car):
def turbo(self):
print("Turbo speed")
my_sportscar = SportsCar()
my_sportscar.drive() # Output: Driving
my_sportscar.stop() # Output: Car stopping
my_sportscar.turbo() # Output: Turbo speed
Using super()
The super() function in Python returns a proxy object that allows you to refer to the parent class. It is commonly used to call the parent class's methods and is essential when extending or overriding methods.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
class Square(Rectangle):
def __init__(self, side_length):
super().__init__(side_length, side_length) # Using super()
my_square = Square(5)
print(my_square.width, my_square.height) # Output: 5 5
Overriding Methods in Derived Classes
Overriding allows a derived class to provide a specific implementation for a method already defined in its base class.
class Animal:
def speak(self):
print("Animal sound")
class Cat(Animal):
def speak(self): # Override the method
print("Meow")
my_cat = Cat()
my_cat.speak() # Output: Meow
Abstract Classes and Interfaces
Abstract Classes
Abstract classes in Python, defined using the abc module, cannot be instantiated and are designed to be subclassed. They can define abstract methods that must be created within any derived non-abstract class.
from abc import ABC, abstractmethod
class AbstractAnimal(ABC):
@abstractmethod
def move(self):
pass
class Fish(AbstractAnimal):
def move(self):
print("Swims")
my_fish = Fish()
my_fish.move() # Output: Swims
Interfaces
In Python, interfaces are usually similar to abstract classes with all methods being abstract. Custom logic is implemented in the concrete classes that inherit from these interfaces.
Summary / Key Takeaways
In this lesson "Inheritance in Python: An In-Depth Look," you have learned:
- Inheritance enables sharing of methods and properties among classes.
- Single inheritance maintains a simple hierarchy, while multiple and multilevel inheritance create complex hierarchies.
- The
super()function simplifies method and attribute access from parent classes. - Method overriding allows derived classes to extend or modify base class behavior.
- Abstract classes enforce the implementation of derived classes and cannot be instantiated themselves.
- Interfaces in Python provide guidelines for implementing methods in derived classes.
