Abstract Classes & Interfaces
Abstract classes define interfaces that subclasses must implement. Use Python's abc module to enforce method contracts.
15 min•By Priygop Team•Updated 2026
Abstract Classes
Abstract Classes
from abc import ABC, abstractmethod
class PaymentProcessor(ABC):
@abstractmethod
def process(self, amount):
pass
@abstractmethod
def refund(self, amount):
pass
def log(self, message): # Concrete method
print(f" LOG: {message}")
class CreditCard(PaymentProcessor):
def process(self, amount):
self.log(f"Credit card charge: ${amount}")
return True
def refund(self, amount):
self.log(f"Credit card refund: ${amount}")
return True
class PayPal(PaymentProcessor):
def process(self, amount):
self.log(f"PayPal payment: ${amount}")
return True
def refund(self, amount):
self.log(f"PayPal refund: ${amount}")
return True
# Can't instantiate abstract class
# p = PaymentProcessor() # TypeError!
# Must implement ALL abstract methods
processors = [CreditCard(), PayPal()]
for p in processors:
p.process(99.99)
print(f" Is PaymentProcessor? {isinstance(p, PaymentProcessor)}")Tip
Tip
Use ABC to define contracts. Subclasses MUST implement all @abstractmethod methods or they can't be instantiated.
Diagram
Loading diagram…
Can't instantiate. Must implement all @abstractmethod.
Common Mistake
Warning
Forgetting to implement all abstract methods in a subclass raises TypeError at instantiation, not at class definition.
Practice Task
Note
(1) Create an abstract Shape with area() and perimeter(). (2) Implement Circle and Rectangle. (3) Try instantiating the abstract class.