Abstract methods and interfaces are essential concepts in object-oriented programming that help define a blueprint for classes. Python provides the abc
module to create abstract methods and interfaces. These concepts enforce a certain structure in the derived classes, ensuring consistency in the program's design.
An abstract method is a method that is declared but does not contain any implementation. Classes that inherit from an abstract class must provide an implementation for all its abstract methods. Abstract methods are created using the @abstractmethod
decorator from the abc
module.
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass class Dog(Animal): def sound(self): return "Bark" class Cat(Animal): def sound(self): return "Meow" # Example usage dog = Dog() cat = Cat() print(dog.sound()) # Output: Bark print(cat.sound()) # Output: Meow
Interfaces are a way to define a set of methods that must be implemented by any class that uses the interface. Python does not have a built-in keyword for interfaces, but abstract classes with only abstract methods can serve as interfaces.
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 def perimeter(self): return 2 * 3.14 * self.radius # Example usage rect = Rectangle(4, 5) circle = Circle(3) print("Rectangle Area:", rect.area()) # Output: 20 print("Rectangle Perimeter:", rect.perimeter()) # Output: 18 print("Circle Area:", circle.area()) # Output: 28.26 print("Circle Perimeter:", circle.perimeter()) # Output: 18.84
Abstract methods and interfaces in Python are powerful tools for enforcing consistent and predictable behavior in object-oriented programs. By using the abc
module, developers can create abstract methods and interfaces that define the structure of derived classes, making the code more robust and maintainable.