Python 语法
Coddy Python 装饰器 课程的第 6 课,共 12 课。
在上一课中,我们了解了如何创建函数装饰器。不过,Python 提供了一种更优雅的方式,可以使用 @ 符号实现这一功能。
例如:
def my_decorator(func):
def wrapper():
print("Before function is called.")
func()
print("After function is called.")
return wrapper
@my_decorator
def my_function():
print("Inside my_function.")运行 my_function() 时,你会看到类似这样的输出:
Before function is called.
Inside my_function.
After function is called.这说明,装饰器函数 my_decorator 能够通过在 my_function 调用前后添加一些额外代码来改变它的行为。
挑战
简单给定了一个函数 add 的代码。
你的任务是像上一课一样,编写一个名为 debug 的函数装饰器,但需要添加一些内容:
- 使用
@符号将函数装饰器debug添加到add。 - 这个调试函数应该支持函数参数。
要让装饰器支持带参数的函数,
def my_decorator(func):
def wrapper(a, b):
print("Before function is called.")
func(a, b)
print("After function is called.")
return wrapper示例:
调用函数 add(2, 3) 时,应该打印:
Calling add with arguments (2, 3)
add returned: 5亲手试试
# 在这里编写代码
def add(a, b):
return a + bPython 装饰器中的所有课
自己练习: Python 在线编译器