In Python, Abstraction is a concept in object-oriented programming (OOP) that focuses on hiding the internal implementation details of a class or method and showing only the necessary features of an object to the outside world.
It allows the programmer to focus on what an object does, rather than how it achieves its functionality.
Python provides the "abc module" for defining abstract base classes.
Abstract base classes are classes that cannot be instantiated on their own, but can be subclassed.
They often define abstract methods, which must be implemented by subclasses.
This enforces a contract that subclasses must adhere to.
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass class Dog(Animal): def make_sound(self): return "Woof!" class Cat(Animal): def make_sound(self): return "Meow!" # Usage dog = Dog() cat = Cat() print(dog.make_sound()) # Output: Woof! print(cat.make_sound()) # Output: Meow!
Animal is an abstract class derived from ABC.
@abstractmethod decorator is used to mark methods as abstract. These methods have no implementation (the pass statement).
Subclasses of Animal must provide implementations for all abstract methods, or they will be considered abstract themselves.
Dog and Cat are concrete subclasses of Animal, and they provide implementations for all abstract methods defined in Animal.
Encapsulation, as discussed earlier, also contributes to abstraction by hiding the internal state of objects and exposing only the necessary functionality through methods.
Interface segregation principle (ISP) suggests that clients should not be forced to depend on interfaces they do not use.
In Python, this can be achieved by creating small, specific interfaces or abstract base classes, which are implemented only by classes that need them.
By using properties, getters, and setters, we can abstract away the implementation details of attribute access and manipulation.
class Rectangle: def __init__(self, length, width): self._length = length self._width = width @property def area(self): return self._length * self._width @property def perimeter(self): return 2 * (self._length + self._width) # Usage rectangle = Rectangle(5, 4) print(rectangle.area) # Output: 20 print(rectangle.perimeter) # Output: 18
Abstraction helps reduce complexity and make code more manageable by focusing on essential aspects and hiding unnecessary details.
It promotes modularity, reusability, and maintainability in software development.