Python Practice › OOP Programs › Program 15
Abstract method
Write a Python program with an abstract class and an abstract method.
Output
Paid Rs 499 by UPI Error: Can't instantiate abstract class Payment without an implementation for abstract method 'pay'
Approach
- Inherit from
ABCand decorate the method with@abstractmethod.
Solution
from abc import ABC, abstractmethod class Payment(ABC): @abstractmethod def pay(self, amount): ... class UPI(Payment): def pay(self, amount): return f"Paid Rs {amount} by UPI" print(UPI().pay(499))try: Payment()except TypeError as e: print("Error:", e)Output
Paid Rs 499 by UPI Error: Can't instantiate abstract class Payment without an implementation for abstract method 'pay'
Line by line
Lines 4-6
Every subclass must implement pay.
Lines 12-15
The abstract class itself cannot be instantiated.
Learn the concept
New to this topic? Read the lesson, then come back.