Abstraction is a key concept in object-oriented programming (OOP) that allows us to focus on essential details while hiding unnecessary or complex implementation details. In Python, abstraction is achieved through the use of abstract classes and interfaces.
An abstract class is a class that cannot be instantiated directly and is meant to be subclassed. It provides a basic structure and functionality for its subclasses, but does not provide a complete implementation for all its methods. Abstract classes can contain abstract methods, which are declared but not implemented. Subclasses of an abstract class are required to implement all abstract methods.
Here is an example of an abstract class in Python:
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass
In this example, the Shape class is an abstract class that defines two abstract methods: area() and perimeter(). These methods are declared but not implemented in the abstract class. Any class that inherits from Shape must provide an implementation for these methods.
An interface is a special case of an abstract class that contains only abstract methods. In Python, interfaces are not defined explicitly, but can be created by defining an abstract class with only abstract methods.
Here is an example of an interface in Python:
from abc import ABC, abstractmethod class Drawable(ABC): @abstractmethod def draw(self): pass
In this example, the Drawable class is an interface that defines a single abstract method: draw(). Any class that inherits from Drawable must provide an implementation for this method.
Here is an example of a class with a destructor: