0
0
Pythonprogramming~5 mins

Abstract base classes overview in Python

Choose your learning style9 modes available
Introduction

Abstract base classes help us create a simple plan for other classes to follow. They make sure certain methods are always there.

When you want to make sure different classes have the same important methods.
When you want to create a common template for many classes.
When you want to prevent creating objects from a class that is only a plan.
When you want to organize your code better by grouping similar classes.
When you want to catch mistakes early by forcing method definitions.
Syntax
Python
from abc import ABC, abstractmethod

class MyBaseClass(ABC):
    @abstractmethod
    def my_method(self):
        pass

Use ABC as the base class to create an abstract base class.

Use @abstractmethod to mark methods that must be defined in child classes.

Examples
This abstract class Animal requires all animals to have a sound method.
Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass
Vehicle is abstract and Car implements the required method.
Python
from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start_engine(self):
        pass

class Car(Vehicle):
    def start_engine(self):
        print("Car engine started")
You cannot create an object from an abstract class directly.
Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

# Trying to create Shape directly will cause an error
# shape = Shape()  # This will raise TypeError
Sample Program

This program shows an abstract class Animal with an abstract method sound. The classes Dog and Cat implement this method. Trying to create an Animal directly will cause an error.

Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        print("Woof!")

class Cat(Animal):
    def sound(self):
        print("Meow!")

# Uncommenting the next line will cause an error because Animal is abstract
# animal = Animal()

print("Creating Dog and Cat objects and calling their sound method:")
dog = Dog()
dog.sound()
cat = Cat()
cat.sound()
OutputSuccess
Important Notes

Time complexity: Abstract base classes do not affect runtime speed significantly; they are a design tool.

Space complexity: No extra memory cost beyond normal class usage.

Common mistake: Forgetting to implement all abstract methods in child classes causes errors.

Use abstract base classes when you want to enforce a common interface for many classes.

Summary

Abstract base classes define a template with methods that must be implemented.

They prevent creating objects from incomplete classes.

They help organize code and catch errors early.