Counting Calls
Completed
Write a decorator count_calls that stores how many times a function was called in a calls attribute. Read n and call a decorated square on 1..n, printing the results on one line, then square.calls.
Input
One integer.
Output
Two lines.
Example
Input
5
Output
1 4 9 16 25 5
Editor
Python
Hints
Functions are objects - you can attach attributes to them.
Solution explanation
Decorators are often used for counting, timing, caching, logging and access checks.
Show solution
import functools
def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def square(x):
return x * x
n = int(input())
print(*[square(i) for i in range(1, n + 1)])
print(square.calls)