Python Abstraction

Abstraction in object-oriented programming is a technique to hide complex implementation details and show only essential information to the user. It provides a simplified view of an object.

Example 1: Basic Abstraction with a `Shape` class


class Shape:
  def __init__(self, name):
    self.name = name

  def area(self):
    raise NotImplementedError("Subclasses must implement this method")


class Circle(Shape):
  def __init__(self, radius):
    super().__init__("Circle")
    self.radius = radius

  def area(self):
    return 3.14159 * self.radius * self.radius


class Rectangle(Shape):
  def __init__(self, width, height):
    super().__init__("Rectangle")
    self.width = width
    self.height = height

  def area(self):
    return self.width * self.height


circle = Circle(5)
rectangle = Rectangle(4, 6)

print(circle.area())  # Output: Area of circle
print(rectangle.area()) # Output: Area of rectangle
    

The `Shape` class defines a common interface (`area()`). The derived classes (e.g., `Circle`) provide the specific implementation details for calculating the area.

Example 2: Hiding Internal Details (Illustrative)


class MyClass:
  def __init__(self):
    self._internal_data = 10  # Protected attribute

  def get_data(self):
    return self._internal_data

  def set_data(self, value):
    self._internal_data = value
   
obj = MyClass()
print(obj.get_data()) #Output: 10
obj.set_data(20) #Modify the internal value.
print(obj.get_data()) #Output: 20
#print(obj._internal_data)  # Accessing the protected attribute directly is discouraged.
    

Internal data (_internal_data) is protected through the getter (`get_data()`) and setter (`set_data()`) methods. This controls how the data is accessed and modified.

Example 3: Using an Abstract Base Class (Illustrative)


from abc import ABC, abstractmethod
    #Import abstract base class from module
class Vehicle(ABC): #Abstract base class
    @abstractmethod  #Forces derived classes to implement method
    def start(self):
        pass


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

car = Car()
car.start() #Output: Car engine started
    

Important Concepts

  • Abstract Base Classes (ABCs): Provide a way to define an interface with method contracts; Python's `abc` module aids in defining these.
  • Encapsulation: Abstraction often relies on encapsulation to hide internal data and method implementation details, as illustrated in the second example.
  • Interface Design: The `Shape` and `Vehicle` example illustrates the use of common interfaces to handle different classes in a more flexible way.
  • Protected Members: A convention (single underscore prefix) exists to suggest attributes are intended for internal class use.