Abstraction

“Abstraction is the process of hiding implementation details and showing only the essential features of an object.”

Purpose & Benefits:

  • Focus on what an object does, not how it does it.
  • Reduces system complexity and decouples modules.
  • Encourages modularity and separates concerns.

Examples:

Minimal Example:

class Shape:
    def area(self):
        raise NotImplementedError("Subclass must implement area()")

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side ** 2

s = Square(5)
print(s.area())  # Output: 25

Realistic Example:

class PaymentProcessor:
    def pay(self, amount):
        raise NotImplementedError

class PayPal(PaymentProcessor):
    def pay(self, amount):
        print(f"Processing ${amount} payment via PayPal")

class CreditCard(PaymentProcessor):
    def pay(self, amount):
        print(f"Processing ${amount} payment via Credit Card")

processor = PayPal()
processor.pay(100)

How to work towards Abstract?

To achieve abstraction, use abstract classes and interfaces

When to use Abstraction?

  • Simplifying complex systems: Abstraction helps provide a clean and consistent interface for complex functionality. For example, in the Shape class, abstraction allows users to call area () without understanding the mathematical calculations, making the system easier to use.
  • Promoting code flexibility: When you anticipate that subclasses will provide specific implementations of generalized behavior, abstraction becomes essential. The Shape class’s abstract area) method ensures that shapes like circles or rectangles implement their area calculations, allowing flexibility in design.
  • Supporting extensibility: Abstraction makes it easier to extend systems without modifying existing code. For instance, adding a new shape like Triangle to the Shape hi erarchy only requires implementing area(), without changing existing code that uses shapes.