Abstraction with ABC in Python

Use the abc module to define abstract base classes and abstract methods.

IntermediateObject-Oriented ProgramsExample 10 of 25
abstraction-with-abc.py
Run in browser
1# Program to demonstrate abstraction with ABC
2
3from abc import ABC, abstractmethod
4
5class Shape(ABC):
6 @abstractmethod
7 def area(self):
8 pass
9
10class Circle(Shape):
11 def __init__(self, radius):
12 self.radius = radius
13
14 def area(self):
15 return 3.14 * self.radius * self.radius
16
17c = Circle(5)
18print("Area:", c.area())

Output

Area: 78.5

What's going on

Shape defines an abstract method 'area'; Circle provides a concrete implementation, enforcing a common interface.