Abstract base classes help us create a simple plan for other classes to follow. They make sure certain methods are always there.
Abstract base classes overview in 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.
Animal requires all animals to have a sound method.from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass
Vehicle is abstract and Car implements the required method.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")
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
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.
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()
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.
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.