Abstract Base Classes
Import ABC and abstractmethod from the abc module.
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)Implementing Abstract Classes
Subclasses MUST implement all abstract methods or they remain abstract.
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())Real-World Example: Payment Processor
Abstraction is ideal for plugin systems where implementations vary but the interface is fixed.
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)Abstract Base Classes: Enforcing a Contract
Abstraction means defining what a class must do without saying how. An Abstract Base Class (ABC) declares required methods but can't be instantiated itself — subclasses must implement those methods or they can't be created either.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): # no body — subclasses MUST provide one
...
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14159 * self.r ** 2
Shape() # ❌ TypeError: Can't instantiate abstract class
Circle(2) # ✅ works — it implemented area()
Why bother, given Python has duck typing? Duck typing fails late — you don't discover a missing method until something calls it at runtime, deep in production. An ABC fails early: forget to implement area() and Python refuses to even construct the object. It turns "hope every subclass has the method" into a guarantee.
| Duck typing | ABC | |
|---|---|---|
| Contract enforced | never (implicit) | at instantiation |
| Error surfaces | when method is called | immediately |
Use an ABC when you have a family of classes that must all share an interface (payment processors, exporters, plugins) and you want the enforcement in one place.
🏋️ Practical Exercise
Build an abstract shape hierarchy:
- Create an abstract base class
Shapewith an abstract methodarea(). - Implement
CircleandRectanglesubclasses that calculate their own area. - Try to instantiate
Shapedirectly and observe theTypeError. - Store several shapes in a list and print each one’s area in a loop.
🔥 Challenge Exercise
Design a Notification abstract base class with an abstract method send(message). Implement EmailNotification, SMSNotification, and PushNotification subclasses, each printing how it delivers the message. Create a list of notifiers and broadcast the same message through all of them. Bonus: add an abstract property channel that each subclass must define.
📋 Summary
- Abstraction hides implementation details and exposes only the essential interface.
- Python supports abstract base classes through the
abcmodule: inherit fromABCand decorate methods with@abstractmethod. - A class with at least one unimplemented abstract method cannot be instantiated — Python raises a
TypeError. - Subclasses must override every abstract method before they can be instantiated.
- Abstract classes can mix abstract methods with concrete methods and shared state.
- Abstraction defines what a class must do; the subclass decides how.
Interview Questions on Abstraction
- What is abstraction in object-oriented programming?
- How do you create an abstract base class in Python?
- What does the
@abstractmethoddecorator do? - Can you instantiate a class that has an unimplemented abstract method? What happens?
- What is the difference between abstraction and encapsulation?
- What module provides abstract base class support in Python?
- Can an abstract class have concrete (implemented) methods as well?
Related Topics
FAQ
Not as a separate language feature. Python uses abstract base classes (ABCs) to achieve the same goal — an ABC with only abstract methods acts as an interface that subclasses must implement.
Because it has unimplemented abstract methods, so it is incomplete. Python blocks instantiation with a TypeError to prevent calling methods that have no body. Once a subclass implements all abstract methods, that subclass can be instantiated.
Yes. You can write a body inside an @abstractmethod and call it from a subclass via super(). The method is still abstract, so subclasses must override it, but they can reuse the base logic.
ABC and ABCMeta? +ABCMeta is the metaclass that enforces abstract method rules. ABC is a convenience base class that already uses ABCMeta, so inheriting from ABC is the simplest way to create an abstract class.

