Python Practice › OOP Programs › Program 15

Abstract method

EasyOOP Programs · 15 of 48

Write a Python program with an abstract class and an abstract method.

Advertisement
Output
Paid Rs 499 by UPI
Error: Can't instantiate abstract class Payment without an implementation for abstract method 'pay'

Approach

  1. Inherit from ABC and decorate the method with @abstractmethod.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs