Back to: Python Programming
Abstract classes are one of the numerous OOP concepts that are essential for creating a template that other classes can use. An abstract class is like a template for other classes. It defines methods that must be included in any class that inherits from it, but it doesn’t provide the actual code for those methods.
Example:
Let’s say you’re building a program to calculate the area of different shapes.
- You create an abstract class called
that says every shape must have anShapearea()method. - But
Shapedoesn’t define howarea()works—because the formula depends on the type of shape. - Each specific shape (like a
CircleorRectangle) inherits from Shape and provides its own version ofarea().
Abstract class: A class that cannot be instantiated on its own; Designed to be subclassed, they are supposed to be parents to children classes.
They can contain abstract methods, which are declared but have no implementation. Abstract classes have a few benefits:
- Prevents instantiation of the class itself (you cannot create an object from a class that’s abstract).
- Any children that inherit, MUST implement ALL inherited abstract methods.
To work with Abstract Classes we need to import ABC (Abstract Base Classes) as well as abstractmethod.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
# Uncommenting the following line will raise an error because we’re missing method implementations
# shape = Shape() # TypeError: Can't instantiate abstract class Shape with abstract methods #area, perimeter
circle = Circle(10)
print(f"Area: {circle.area()} cm squared")
print(f"Perimeter: {circle.perimeter()} cm")
Outputs:
Area: 314.159 cm squared
Perimeter: 62.8318 cm
In the above example, the class Circle inherits methods area and perimeter from the abstract class Shape. The class Circle MUST implement an area and perimeter method.
Any subclass of an abstract class is guaranteed to implement the decorated methods thanks to the abstractmethod decorator. As a precaution, it stops subclasses from being created that do not have the necessary capabilities.
Python reports a TypeError when a subclass is attempted to be instantiated if it does not override all abstract methods. This stringent enforcement lowers the likelihood of defects and improves code stability by assisting developers in identifying implementation flaws early.
It also guarantees that all concrete subclasses follow the abstract class’s intended behaviour and design. In Python, defining an abstract class entails using the abstractmethod decorator and subclassing from ABC. By doing this, programmers can lay the groundwork for other classes by defining the methods that need to be used
Practical example: abstract class implementation
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, brand):
self.brand = brand
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Motorcycle(Vehicle):
def start_engine(self):
print(f"{self.brand} motorcycle engine started")
def stop_engine(self):
print(f"{self.brand} motorcycle engine stopped")
motorcycle = Motorcycle("Yamaha")
motorcycle.start_engine()
motorcycle.stop_engine()
Outputs:
Yamaha motorcycle engine started
Yamaha motorcycle engine stopped
This code snippet demonstrates the use of abstract base classes in Python to define a blueprint for a group of related classes. Here’s a breakdown:
- Imports:
from abc import ABC, abstractmethodimports the necessary components to create abstract base classes. - Abstract Base Class:
class Vehicle(ABC):defines an abstract base class namedVehicle. It inherits fromABC, making it an abstract class that cannot be instantiated directly. - Constructor:
def __init__(self, brand):initializes theVehicleclass with abrandattribute. - Abstract Methods:
@abstractmethoddecorator indicates thatstart_engineandstop_engineare abstract methods. Any subclass ofVehiclemust implement these methods.
- Concrete Subclass:
class Motorcycle(Vehicle):is a concrete class that inherits fromVehicle. It provides specific implementations for thestart_engineandstop_enginemethods. - Method Implementation:
start_engineandstop_engineinMotorcycleprint messages indicating the engine’s state, using thebrandattribute.
- Instantiation and Method Calls:
motorcycle = Motorcycle("Yamaha")creates an instance ofMotorcyclewith the brand “Yamaha”.motorcycle.start_engine()andmotorcycle.stop_engine()call the implemented methods, resulting in printed messages.
The code aims to demonstrate how abstract classes can define a common interface for subclasses, ensuring they implement specific methods. Here, Motorcycle provides concrete behaviour for starting and stopping an engine, adhering to the Vehicle interface.