Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Magic Methods
0/1
Python
About Lesson

Abstraction is one of the fundamental principles of Object-Oriented Programming (OOP). It is the process of hiding the internal implementation details of a feature and showing only the essential functionalities to the users. In Python, abstraction allows developers to focus on what an object does rather than how it performs the task.
For example, when you use a car, you interact with functionalities like “start the engine,” “drive,” or “apply brakes,” but you don’t need to know the internal working of the engine or the braking system. Similarly, in programming, abstraction hides complex details and exposes only the necessary parts.

In Python, abstraction is implemented using abstract classes and the @abstractmethod decorator, which are part of the abc module (Abstract Base Classes).

  1. Abstract Class:
    • A class that cannot be instantiated.
    • It is meant to be inherited by subclasses that implement the abstract methods.
    • Abstract classes serve as blueprints for derived classes.
  2. Abstract Method:
    • A method that is declared but contains no implementation (i.e., it has no body).
    • Subclasses must override and implement abstract methods.
  1. Import the ABC class and the abstractmethod decorator from the abc module.
  2. Define an abstract class by inheriting from ABC.
  3. Use the @abstractmethod decorator to define abstract methods within the abstract class.
  4. Create a subclass that inherits from the abstract class and provides concrete implementations for the abstract methods.

Example:

Python
from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class CreditCardPayment(Payment):
    def pay(self, amount):
        print(f"Paid {amount} using Credit Card.")

class PayPalPayment(Payment):
    def pay(self, amount):
        print(f"Paid {amount} using PayPal.")

class BankTransferPayment(Payment):
    def pay(self, amount):
        print(f"Paid {amount} using Bank Transfer.")

# Using the concrete classes
payment1 = CreditCardPayment()
payment1.pay(100)

payment2 = PayPalPayment()
payment2.pay(200)

payment3 = BankTransferPayment()
payment3.pay(300)