Refactor to Use ABC
Advanced · Refactor · from Python Abstract Base Classes: Enforce Interfaces with ABC
From the lesson: Python Abstract Base Classes: Enforce Interfaces with ABC
Imagine you're an architect handing blueprints to a construction crew. The blueprint says "there must be a front door here" and "the roof goes here." The crew can choose the materials and style, but they must include those parts. If they skip the front door, the building inspector will reject the project.
Read the lessonThe code below uses NotImplementedError to simulate abstract methods. Refactor it to use ABC and @abstractmethod instead. Keep the same output:
Area: 50
Area: 78.5Remove all NotImplementedError raises and use proper abstract methods.
class Shape:
def area(self):
raise NotImplementedError('Subclass must implement')
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r ** 2
for s in [Rectangle(5, 10), Circle(5)]:
print(f'Area: {s.area()}')
More Abstract Base Class exercises
- Create an Animal ABCIntermediate
- Predict the ABC ErrorIntermediate
- Fix the Broken ABCIntermediate
- Abstract Property: Employee TypesAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz