始める無料で始める

カウンター

新しい Web アプリを開発していて、各関数が何回呼び出されるのかが気になりました。そこで、デコレートした各関数に呼び出し回数のカウンターを付けるデコレータを書くことにします。将来、この情報を使って、アプリで使われなくなったコードの箇所がないかを判断し、削除できるかもしれません。

この演習はコースの一部です

Python関数の書き方

コースを見る

演習の手順

  • デコレート対象の関数を呼び出し、その結果を返してください。
  • 新しく作ったデコレート済みの関数を返してください。
  • foo()counter() デコレータでデコレートしてください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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))
コードを編集して実行