LearnFrenzy
Sign in Take a free test

Decorators · Predict the Output · Question 8

Counting calls with a wrapper attribute Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following Python program?

main.py
def counted(f):
    def wrapper(*a):
        wrapper.calls += 1
        return f(*a)
    wrapper.calls = 0
    return wrapper

@counted
def square(x):
    return x * x

total = sum(square(i) for i in range(4))
print(total, square.calls)
  • A 14 1
  • B 30 4
  • C 14 4 Correct
  • D 14 0
Correct Answer: Option C

0 + 1 + 4 + 9 = 14, from four calls through the wrapper.

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