Learn how Python Abstract Base Classes (ABC) enforce method implementation in child classes. See what happens if abstract methods are missing, with code examples and fixes. Perfect for OOP developers!
In Python, an Abstract Base Class (ABC) is a class that cannot be instantiated directly. Instead, it serves as a blueprint for other classes (child classes) by defining abstract methods that must be implemented in the child classes.
pass
or a docstring).If a child class does not implement all abstract methods from its parent ABC, Python will raise a TypeError
when you try to create an instance of that child class.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle): # Only implements `start()`, missing `stop()`
def start(self):
print("Starting the car engine")
# Attempting to create an instance of Car
car = Car() # โ TypeError: Can't instantiate abstract class Car with abstract method stop
Error:
TypeError: Can't instantiate abstract class Car with abstract method stop
Car
did not implement stop()
, Python prevents instantiation.The child class must implement all abstract methods from the parent ABC.
class Car(Vehicle):
def start(self):
print("Starting the car engine")
def stop(self): # Now properly implemented
print("Stopping the car engine")
car = Car() # โ
Works fine
car.start() # Output: "Starting the car engine"
car.stop() # Output: "Stopping the car engine"
TypeError
.This is particularly useful in large projects where multiple developers need to ensure that certain methods are always available in derived classes. ๐