開始使用免費開始

幫你的函式加上標籤

「加上標籤」表示你為某個東西指定了一或多個作為標籤的字串。例如,我們常會替電子郵件或照片加上標籤,之後才方便搜尋。你決定寫一個裝飾器,讓你可以用任意數量的標籤來標記你的函式。你可以用這些標籤做很多事:

  • 加上誰曾經維護或開發該函式的資訊,讓使用者遇到問題時可以知道要詢問誰。
  • 將函式標示為「experimental」,提醒使用者未來輸入與輸出可能會改變。
  • 標記任何你打算在未來版本中移除的函式。
  • 等等。

本練習屬於課程

Python 函式寫作

檢視課程

練習說明

  • 定義一個新的裝飾器,命名為 decorator(),並讓 tag() 回傳它。
  • 確保被裝飾後的函式能保留其中介資料。
  • 呼叫被裝飾的函式並回傳其結果。
  • 回傳這個新的裝飾器。

動手互動練習

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

def tag(*tags):
  # Define a new decorator, named "decorator", to return
  def ____(____):
    # Ensure the decorated function keeps its metadata
    @____(____)
    def wrapper(*args, **kwargs):
      # Call the function being decorated and return the result
      return ____(____, ____)
    wrapper.tags = tags
    return wrapper
  # Return the new decorator
  return ____

@tag('test', 'this is a tag')
def foo():
  pass

print(foo.tags)
編輯並執行程式碼