Advanced functions and decorators · 13 / 15 Exercise Medium

Decorator that counts calls

Objective

Create a Python program with a decorator that keeps track of how many times a function has been called.

Instructions

  • Define def count_calls(function). Its wrapper(*args, **kwargs) adds 1 to a counter (an attribute of the wrapper itself: wrapper.calls, which starts at 0) and calls the original function, returning its result. count_calls returns wrapper.
  • Define greet(name), which returns "Hello, NAME", and decorate it with @count_calls.
  • Read an integer n and then n names, one per line. Show the greeting for each one.
  • At the end show Calls: K, reading greet.calls.
Input
2
Ana
Luis
Output
Hello, Ana
Hello, Luis
Calls: 2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise