Abstract Base Classes (ABC)
- An Abstract Base Class (ABC) is a class that cannot be instantiated on its own. It is designed to define a common interface (a set of method names and signatures) that subclasses must implement.
- Polymorphism occurs when different subclasses implement these methods in different ways, and code can work with any of the subclasses interchangeably through the abstract base class interface.
- An abstract class is a class that contains only a list of methods and is used to enforce method implementation in the inheriting classes
- An abstract method is a method that has a declaration but does not have an implementation
- Import Abstract Base Class
import ABC
- Import Abstract Base Class
- The @abstractmethod decorator is used to define an abstract method within an abstract base class (ABC)
How to Define an Abstract Base Class
- Python provides the abc module for this.
- ABC is the base class for all abstract classes.
- @abstractmethod is used to mark methods that must be implemented in a subclass.
Example: Polymorphism with ABC
Step 1: Define an abstract base class.
- This defines the interface all shapes must follow.
Step 2: Create concrete subclasses
- Each subclass provides its own implementation of area() and perimeter().
Step 3: Use them polymorphically
- Even though Rectangle and Circle are different classes, the function print_shape_info() works with both — this is polymorphism through ABCs.
isinstance() function
The isinstance() function in Python is used to check if an object is an instance of a specified class or if it is an instance of a subclass of that class.
Here's the general syntax:
isinstance(object, classinfo) |
- object: The object to be checked
- classinfo: A class or a tuple of classes to be checked against
In the above example, car_instance is an instance of both the Car class and its parent class Vehicle, so isinstance() returns True for both checks.
Output:
True True |