Write a Shape base class and two subclasses.
Shape
Circle(radius) # inherits from Shape
Square(side) # inherits from Shape
Shape.area(self) — Shape itself doesn't know how to compute an area; raise NotImplementedError.Circle(radius) inherits from Shape, stores radius, and overrides area() to return round(3.14159 * radius ** 2, 2).Square(side) inherits from Shape, stores side, and overrides area() to return side ** 2.Circle(2).area() // → 12.57
Square(4).area() // → 16.0
Shape().area() // raises NotImplementedError
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return round(3.14159 * self.radius ** 2, 2)
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape): and class Square(Shape): both inherit from Shape — that inheritance relationship doesn't actually give them much directly here (Shape has no __init__ and no useful attributes to inherit), but it does mean both Circle and Square are Shapes, which matters if other code ever wants to treat any shape uniformly (as the previous lesson's total_area(shapes) example showed).
Each subclass defines its own area(), completely overriding Shape.area — when you call Circle(2).area(), Python uses Circle's version, not Shape's. That's the whole point of Shape.area raising NotImplementedError: it's a deliberate placeholder, signaling "any real shape must provide its own version of this" — and if a subclass forgot to override it, calling .area() on that subclass would fall back to Shape's version and raise, immediately revealing the mistake rather than silently returning a wrong number.
Calling Shape() directly and then .area() on it exercises exactly that base-class behavior — there's no subclass involved at all, so it's Shape.area itself that runs, and raises.
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return round(3.14159 * self.radius ** 2, 2)
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.