SyntaxStudy
Sign Up
Python Abstract Methods with @abstractmethod
Python Intermediate 4 min read

Abstract Methods with @abstractmethod

@abstractmethod

@abstractmethod from abc forces subclasses to implement a method. Classes with abstract methods cannot be instantiated.

Example
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14159 * self.r ** 2

c = Circle(5)
print(c.area())  # 78.54
Pro Tip

ABCs act as interfaces in Python, enforcing contracts on subclasses.