Abstract Classes in Python

Abstract Classes in Python

This article explains abstract classes in Python.

We will explain the basic mechanism of abstract classes using the abc module, provide practical examples, and describe everything with accompanying code.

YouTube Video

Abstract Classes in Python

Python's abc module (Abstract Base Classes) is part of the standard library and is used to define abstract classes, providing a template for methods that a class should implement. Using this module enhances flexibility and robustness in class design.

What is an Abstract Class?

Abstract classes are classes used to define a common interface for concrete (instantiable) classes. Abstract classes cannot be instantiated themselves; a concrete implementation must be provided in derived (sub)classes.

The abc module allows you to define abstract methods or properties and enforce their implementation in the inheriting classes. If even one abstract method is not implemented, the class cannot be instantiated.

How to Use the abc Module

To create an abstract class using the abc module, inherit from the ABC class and define abstract methods using the @abstractmethod decorator.

 1from abc import ABC, abstractmethod
 2
 3# Definition of the abstract base class
 4class Animal(ABC):
 5
 6    @abstractmethod
 7    def sound(self):
 8        pass
 9
10# Concrete implementation in the subclass
11class Dog(Animal):
12    def sound(self):
13        return "Woof!"
14
15class Cat(Animal):
16    def sound(self):
17        return "Meow!"

Here, the Animal class is defined as an abstract class and includes an abstract method called sound. This method must be concretely implemented in the subclasses. Dog and Cat inherit from Animal and each implement the sound method.

Instantiating Abstract Classes

Abstract classes cannot be instantiated directly. For example, attempting to instantiate the Animal class itself will result in an error.

1animal = Animal()  # TypeError: Can't instantiate abstract class Animal with abstract methods sound
  • When trying to instantiate an abstract class, Python determines that there are unimplemented abstract methods and raises a TypeError. If all required abstract methods are implemented in the subclass, instantiation becomes possible.

Multiple Abstract Methods

It is also possible for a class to have multiple abstract methods. Unless all abstract methods are implemented in a subclass, the class remains an abstract class.

 1from abc import ABC, abstractmethod
 2
 3class Vehicle(ABC):
 4
 5    @abstractmethod
 6    def start_engine(self):
 7        pass
 8
 9    @abstractmethod
10    def stop_engine(self):
11        pass
12
13class Car(Vehicle):
14    def start_engine(self):
15        return "Car engine started"
16
17    def stop_engine(self):
18        return "Car engine stopped"

In this example, the Vehicle class has two abstract methods, and the Car class can only be instantiated after implementing both methods.

Defining Abstract Properties

The abc module supports not only abstract methods but also abstract properties. This enables enforcing the implementation of properties in derived classes.

 1from abc import ABC, abstractmethod
 2
 3class Shape(ABC):
 4
 5    @property
 6    @abstractmethod
 7    def area(self):
 8        pass
 9
10class Circle(Shape):
11    def __init__(self, radius):
12        self.radius = radius
13
14    @property
15    def area(self):
16        return 3.14159 * (self.radius ** 2)
  • In this example, the Shape class has an abstract property area, and the subclass Circle concretizes this property. In this way, using abstract classes to enforce property implementation helps maintain code consistency.

Using isinstance() and issubclass()

By using abstract classes, you can confirm class inheritance relationships with isinstance() or issubclass(), improving code safety and flexibility.

 1from abc import ABC, abstractmethod
 2
 3# Definition of the abstract base class
 4class Animal(ABC):
 5
 6    @abstractmethod
 7    def sound(self):
 8        pass
 9
10# Concrete implementation in the subclass
11class Dog(Animal):
12    def sound(self):
13        return "Woof!"
14
15class Cat(Animal):
16    def sound(self):
17        return "Meow!"
18
19class Vehicle(ABC):
20
21    @abstractmethod
22    def start_engine(self):
23        pass
24
25    @abstractmethod
26    def stop_engine(self):
27        pass
28
29class Car(Vehicle):
30    def start_engine(self):
31        return "Car engine started"
32
33    def stop_engine(self):
34        return "Car engine stopped"
35
36print("Dog() is an Animal? -> ", isinstance(Dog(), Animal))   # True
37print("Dog is subclass of Animal? -> ", issubclass(Dog, Animal))  # True
38print("Cat() is a Vehicle? -> ", isinstance(Cat(), Vehicle))  # False

isinstance() is used to check if an object is an instance of a specified class, and issubclass() is used to check if a class is a subclass of a specified class.

Summary

By designing abstract classes using the abc module, you can clarify the interface between classes and enforce the implementation of required methods and properties. This helps maintain code consistency and reduces errors, making it particularly useful for large-scale projects.

Abstract classes are an important tool in Python that support flexible object-oriented programming, enhancing class reusability and maintainability.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video