Advertisement
🏗️ OOP

Python Abstraction – Abstract Classes and Interfaces

Abstraction hides complex implementation details and shows only the necessary interface. In Python, abstraction is achieved using Abstract Base Classes (ABCs). You define what a class must do without specifying how, forcing subclasses to provide the implementation.

⏱️ 18 min read🎯 Intermediate📅 Updated 2026

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, stop

Implementing 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 OK

Real-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.99
Advertisement

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 typingABC
Contract enforcednever (implicit)at instantiation
Error surfaceswhen method is calledimmediately

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:

  1. Create an abstract base class Shape with an abstract method area().
  2. Implement Circle and Rectangle subclasses that calculate their own area.
  3. Try to instantiate Shape directly and observe the TypeError.
  4. 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 abc module: inherit from ABC and 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 @abstractmethod decorator 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?

FAQ

Does Python have interfaces like Java? +

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.

Why can’t I instantiate an abstract class? +

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.

Can an abstract method have a default implementation? +

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.

What is the difference between 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.