An abstract class is a class that cannot be instantiated directly. Its main purpose is to be inherited by other classes that implement the methods defined as abstract in the base class.
In Python, abstract classes are implemented using the abc (Abstract Base Classes) module. This module provides tools for defining abstract classes and methods.
from abc import ABC, abstractmethodDefining an Abstract Class
To define an abstract class, it must inherit from ABC and use the @abstractmethod decorator to mark the methods that must be implemented by subclasses.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
def sleep(self):
print("The animal is sleeping.")In this example,
Animalis an abstract class with an abstract methodmake_sound- A concrete method
sleep.
Implementing Derived Classes
Classes that inherit from an abstract class must implement all abstract methods. If a subclass does not implement an abstract method, it also becomes an abstract class and cannot be instantiated.
Let’s see how to implement our abstract class Animal
class Dog(Animal):
def make_sound(self):
print("The dog barks.")
class Cat(Animal):
def make_sound(self):
print("The cat meows.")In this example, Dog and Cat are subclasses of Animal that implement the abstract method make_sound.
Mixed Classes
An abstract class can have both abstract methods and concrete methods. Concrete methods provide a default implementation that can be inherited or overridden by subclasses.
Let’s see it with an example,
class Vehicle(ABC):
@abstractmethod
def drive(self):
pass
def start(self):
print("The vehicle is started.")
class Car(Vehicle):
def drive(self):
print("The car is driving.")
class Motorcycle(Vehicle):
def drive(self):
print("The motorcycle is driving.")In this example,
Vehiclehas an abstract methoddriveand a concrete methodstart.- The subclasses
CarandMotorcycleimplementdrivebut inheritstart.