LearnFrenzy
Sign in Take a free test

Inheritance and Polymorphism · Predict the Output · Question 5

Polymorphism over a list of shapes Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Python program?

main.py
class Shape:
    def area(self): return 0
class Square(Shape):
    def __init__(self, s): self.s = s
    def area(self): return self.s ** 2
class Rect(Shape):
    def __init__(self, w, h): self.w, self.h = w, h
    def area(self): return self.w * self.h

shapes = [Square(3), Rect(2, 5), Shape()]
print([s.area() for s in shapes], sum(s.area() for s in shapes))
  • A [9, 10, 0] 19 Correct
  • B [0, 0, 0] 0
  • C [9, 10] 19
  • D AttributeError
Correct Answer: Option A

Each object uses its own area(); the base Shape returns 0.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links