開始使用免費開始

Counter

你正在開發一個新的網頁應用,並且想知道其中每個函式被呼叫了多少次。因此,你決定撰寫一個裝飾器,替每個被你裝飾的函式加上一個計數器。未來你可以利用這些資訊來判斷是否有程式碼區塊已經不再被應用使用,因而可以移除。

本練習屬於課程

Python 函式寫作

檢視課程

練習說明

  • 呼叫被裝飾的函式並回傳結果。
  • 回傳新的裝飾後函式。
  • 使用 counter() 裝飾器來裝飾 foo()

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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))
編輯並執行程式碼