LearnFrenzy
Sign in Take a free test

Decorators · Predict the Output · Question 14

Decorators created in a loop Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Python program?

main.py
def add(n):
    def deco(f):
        return lambda x: f(x) + n
    return deco

funcs = []
for n in [1, 10, 100]:
    funcs.append(add(n)(lambda x: x))

print([f(0) for f in funcs])
  • A [100, 100, 100]
  • B [0, 0, 0]
  • C [1, 11, 111]
  • D [1, 10, 100] Correct
Correct Answer: Option D

Each call add(n) creates a new scope holding that n, so the late-binding trap does not apply here.

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