🎭 Python OOP β€” Abstraction

Introduction 🌟

**Abstraction** in Object-Oriented Programming (OOP) is the concept of hiding unnecessary implementation details and showing only the essential features to the user. Python provides abstraction mainly through **abstract classes** and **abstract methods** using theabc (Abstract Base Class) module.

Note

πŸ’‘ Abstraction = *What it does* (shown) ⭐
Implementation = *How it does* (hidden) πŸ”’

1. Real-Life Example of Abstraction 🌍

When you drive a car, you use a steering wheel, pedals, etc., but you don't need to understand how the engine works internally. This is **abstraction** β€” exposing essential features, hiding complexity.

2. Abstraction in Python Using Abstract Classes 🧱

Python allows you to create abstract classes using ABC and @abstractmethod.

abstract_basic.py

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Bark"

d = Dog()
print(d.sound())

βœ” Animal is an abstract class
βœ” sound() is an abstract method
βœ” Any subclass **must** implement the abstract method

3. Why Use Abstraction? πŸ€”

  • βœ” Hides unnecessary details
  • βœ” Provides a clear structure for subclasses
  • βœ” Enforces method implementation
  • βœ” Makes code cleaner and more maintainable
  • βœ” Helps build large applications with rules & consistency

4. Abstract Class Cannot Be Instantiated ❌

cannot_instantiate.py

a = Animal()    # ❌ Error: Can't instantiate abstract class

Note

βœ” Abstract classes act as blueprints; they are not objects themselves.

5. Example with Multiple Abstract Methods 🧩

multiple_abstract_methods.py

from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start(self): pass

    @abstractmethod
    def stop(self): pass

class Car(Vehicle):
    def start(self):
        print("Car started")

    def stop(self):
        print("Car stopped")

c = Car()
c.start()
c.stop()

βœ” Every abstract method must be implemented by the child class.

6. Abstract Class with Constructor 🎯

abstract_constructor.py

from abc import ABC, abstractmethod

class Shape(ABC):
    def __init__(self, color):
        self.color = color

    @abstractmethod
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side, color):
        super().__init__(color)
        self.side = side

    def area(self):
        return self.side ** 2

s = Square(5, "blue")
print(s.area())

βœ” Abstract classes can have constructors
βœ” Child classes must call them using super()

7. Example: Payment System πŸ’³

payment_example.py

from abc import ABC, abstractmethod

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

class CashPayment(Payment):
    def pay(self, amount):
        print(f"Paid {amount} in cash")

class CardPayment(Payment):
    def pay(self, amount):
        print(f"Paid {amount} via card")

p = CardPayment()
p.pay(500)

8. Partially Abstract Classes (Concrete + Abstract Methods) ⚑

partial_abstract.py

from abc import ABC, abstractmethod

class Device(ABC):
    def power_on(self):
        print("Device is ON")

    @abstractmethod
    def run(self):
        pass

class Laptop(Device):
    def run(self):
        print("Laptop running...")

l = Laptop()
l.power_on()
l.run()

Note

βœ” Abstract classes can have both normal and abstract methods.

9. Using Abstraction for Enforcing Rules πŸ›‘οΈ

enforced_rules.py

from abc import ABC, abstractmethod

class Database(ABC):
    @abstractmethod
    def connect(self): pass

    @abstractmethod
    def disconnect(self): pass

class MySQL(Database):
    def connect(self):
        print("Connected to MySQL")

    def disconnect(self):
        print("Disconnected from MySQL")

db = MySQL()
db.connect()
db.disconnect()

10. Abstraction vs Encapsulation βš”οΈ

AbstractionEncapsulation
Shows essential features onlyHides data using private/protected members
Achieved using abstract classes/methodsAchieved using getters/setters
Focuses on β€œWhat?”Focuses on β€œHow?” protection

11. Best Practices πŸ’‘

  • βœ” Use abstraction to enforce method rules across subclasses
  • βœ” Keep abstract classes simple and meaningful
  • βœ” Use descriptive names for abstract methods
  • βœ” Avoid adding unnecessary abstract methods

Conclusion πŸŽ‰

>>β€œAbstraction lets you focus on what matters, hiding unnecessary complexity β€” the true power of clean OOP design.” ✨

You now fully understand Abstraction in Python! Want the next topic? Try Encapsulation, Inheritance, Polymorphism, or Magic Methods. Just tell me! 😊