Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

装饰器


```markdown 装饰器允许您对可调用对象进行简单修改,比如函数方法或类。在本教程中我们将处理函数。语法

等同于:

正如您所见,装饰器只是另一个函数,它接受一个函数并返回一个函数。例如,您可以这样做:

这将使函数重复运行两次。

您还可以更改输出

更改输入

并进行检查。

假设您想用一个可变的量来乘以输出。您可以定义装饰器并如下使用:

您可以对旧函数做任何事情,甚至完全忽略它!高级装饰器还可以操作文档字符串和参数数量。 要获取一些炫酷的装饰器,请访问 http://wiki.python.org/moin/PythonDecoratorLibrary

Exercise

创建一个装饰器工厂,它返回一个装饰函数为单参数的装饰器。工厂应接收一个参数,一个类型,然后返回一个装饰器,该装饰器应检查输入是否是正确的类型。如果类型错误,则应打印("Bad Type")(实际上,应引发一个错误,但本教程中不包括错误引发)。如果感到困惑,请查看教程代码和期望输出(我肯定会这样的)。使用 isinstance(object, type_of_object) 或 type(object) 可能会有所帮助。 ```

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy