IniziaInizia gratis

Counter

You're working on a new web app, and you are curious about how many times each of the functions in it gets called. So you decide to write a decorator that adds a counter to each function that you decorate. You could use this information in the future to determine whether there are sections of code that you could remove because they are no longer being used by the app.

Questo esercizio fa parte del corso

Writing Functions in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Call the function being decorated and return the result.
  • Return the new decorated function.
  • Decorate foo() with the counter() decorator.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

def counter(func):
  def wrapper(*args, **kwargs):
    wrapper.count += 1
    # Call the function being decorated and return the result
    return ____
  # Set count to 0 to initialize call count for each new decorated function
  wrapper.count = 0
  # Return the new decorated function
  ____

# Decorate foo() with the counter() decorator
____
def foo():
  print('calling foo()')
  
foo()
foo()

print('foo() was called {} times.'.format(foo.count))
Modifica ed esegui il codice