开始使用免费开始使用

给您的函数打标签

给某个对象打标签,意味着为它添加一个或多个充当标记的字符串。例如,我们常给邮件或照片打标签,方便之后搜索。您决定编写一个装饰器,让您可以用任意标签列表为函数打标签。您可以将这些标签用于多种场景:

  • 添加谁参与了该函数的信息,方便用户遇到问题时知道该向谁咨询。
  • 将函数标记为 "experimental",让用户了解其输入和输出在未来可能会变动。
  • 标记计划在未来版本中移除的函数。
  • 等等。

本练习是课程的一部分

Python 函数编写

查看课程

练习说明

  • 定义一个名为 decorator() 的新装饰器,并返回它。
  • 确保被装饰函数保留其元数据。
  • 调用被装饰的函数并返回结果。
  • 返回这个新的装饰器。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
编辑并运行代码