Abstract Base Classes
Import ABC and abstractmethod from the abc module.
Python
from abc import ABC, abstractmethod
class Vehicle(ABC): # Abstract class
@abstractmethod
def start(self):
"""Start the vehicle."""
pass
@abstractmethod
def stop(self):
"""Stop the vehicle."""
pass
def status(self): # Concrete method β shared by all
return "Vehicle status OK"
# You CANNOT instantiate abstract classes:
try:
v = Vehicle()
except TypeError as e:
print(e)βΆ Output
Can't instantiate abstract class Vehicle with abstract methods start, stopImplementing Abstract Classes
Subclasses MUST implement all abstract methods or they remain abstract.
Python
class Car(Vehicle):
def start(self):
return "Car engine starting... vroom!"
def stop(self):
return "Car braking to a stop."
class ElectricScooter(Vehicle):
def start(self):
return "Scooter motor activating silently."
def stop(self):
return "Scooter regenerative braking."
for v in [Car(), ElectricScooter()]:
print(v.start())
print(v.status())βΆ Output
Car engine starting... vroom!
Vehicle status OK
Scooter motor activating silently.
Vehicle status OKReal-World Example: Payment Processor
Abstraction is ideal for plugin systems where implementations vary but the interface is fixed.
Python
from abc import ABC, abstractmethod
class PaymentProcessor(ABC):
@abstractmethod
def charge(self, amount): ...
@abstractmethod
def refund(self, amount): ...
class StripeProcessor(PaymentProcessor):
def charge(self, amount):
return f"Stripe charged ${amount}"
def refund(self, amount):
return f"Stripe refunded ${amount}"
class PayPalProcessor(PaymentProcessor):
def charge(self, amount):
return f"PayPal charged ${amount}"
def refund(self, amount):
return f"PayPal refunded ${amount}"
# Works with ANY payment processor
def checkout(processor: PaymentProcessor, amount):
print(processor.charge(amount))
checkout(StripeProcessor(), 99.99)
checkout(PayPalProcessor(), 49.99)βΆ Output
Stripe charged $99.99
PayPal charged $49.99Ad β 336Γ280