πŸ“¦ Abstraction in Python

Hiding Implementation, Showing Functionality

πŸ”Ή Definition

Abstraction in Python is a concept of hiding unnecessary internal details and showing only the important features to the user. In simple human words, abstraction means what an object does, not how it does it.

It helps programmers focus on usage instead of complex logic. When abstraction is used, the user interacts with a simplified interface, while the internal working remains hidden in the background. This makes programs easier to understand, manage, and modify.

Article Algo

βœ… Why Use Abstraction?

  • Hides complex implementation details
  • Improves code readability
  • Enhances security
  • Makes programs scalable and flexible

πŸ“Œ Syntax

In Python, abstraction is mainly achieved using:

  • Abstract classes
  • Abstract methods

These are provided by the abc (Abstract Base Class) module.

from abc import ABC, abstractmethod

class ClassName(ABC):
  @abstractmethod
  def method_name(self):
    pass

πŸ“˜ Example Program (Abstraction in Python)

from abc import ABC, abstractmethod

class Vehicle(ABC):

  @abstractmethod
  def start(self):
    pass

class Car(Vehicle):
  def start(self):
    print("Car starts with a key")

class Bike(Vehicle):
  def start(self):
    print("Bike starts with a self button")

c = Car()
c.start()

b = Bike()
b.start()

πŸ“Œ Explanation

In this example, Vehicle is an abstract class. It contains an abstract method called start(), but it does not define how the vehicle starts. The method only declares what must be done, not how it should be done.

The Car and Bike classes inherit the Vehicle class and provide their own implementation of the start() method. This means each vehicle starts differently, but from the user’s perspective, they only need to call start().

Abstraction ensures that all vehicle types follow the same structure while allowing flexibility in implementation. It also prevents creating objects of incomplete classes. If a child class does not implement all abstract methods, Python will raise an error.

πŸ”‘ Key Points to Remember

  • Abstraction hides internal details
  • Implemented using abc module
  • Abstract methods have no body
  • Child classes must implement abstract methods

πŸ“Œ Conclusion

Abstraction improves code clarity, security, and flexibility. It hides complexity, enforces structure, and allows developers to build scalable applications easily.