Abstraction
Python · Functions & OOP
Theory
Abstraction means showing only what a caller needs and hiding how it is done. A PaymentMethod base class defines one method, pay(amount), and each concrete class (CreditCard, UPI) fills in the details. Code that takes payments only calls pay(); it never needs to know how a card is charged or a UPI request is sent.
The simplest way to define the interface is a base method that raises NotImplementedError, as in the example. The more formal way uses the abc module: class PaymentMethod(ABC) with @abstractmethod def pay(...). Then Python refuses to create an object of any class that has not implemented every abstract method, catching mistakes when the object is created instead of later when the method is called.
Why we use it
Abstraction reduces complexity: callers work with a small, stable interface, and you can add or swap implementations (a new wallet) without touching the code that uses them.
When to use it
Use it when several classes must offer the same operations in different ways, such as payment methods, file exporters or data sources. Skip it for a single implementation; an extra abstract layer then adds code without benefit.
How it works
- Checkout calls method.pay(100)
- Caller only knows the PaymentMethod interface
- Is it a CreditCard object? Yes: CreditCard.pay charges the card. No: UPI.pay sends a UPI request.
- Details stay hidden inside the subclass
- Payment done; caller code unchanged
Syntax
class Base:
def action(self):
raise NotImplementedErrorExample
class PaymentMethod:
def pay(self, amount):
raise NotImplementedError
class CreditCard(PaymentMethod):
def pay(self, amount):
print(f'Charged {amount} to card')
CreditCard().pay(100)Key points
- Python typically uses the abc module for formal abstract base classes
- Callers depend only on the interface (pay), not the underlying details
- @abstractmethod blocks creating objects that skip the method
- raise NotImplementedError is the lightweight, informal version
- Abstraction hides 'how'; encapsulation protects 'what' (the data)