在Python中,装饰器是一种可以修改另一个函数的行为而不改变其源代码的函数。装饰器用于为函数添加功能,例如日志记录、缓存或修改参数或返回值。
以下是Python中简单装饰器的示例:
def my_decorator(func): def wrapper(): print('Before the function is called.') func() print('After the function is called.') return wrapper@my_decoratordef say_hello(): print('Hello!')# 调用装饰过的函数say_hello()
在这个示例中,my_decorator 是一个接受另一个函数 func 作为参数并返回一个新函数 wrapper 的函数。wrapper 函数在调用原始的 func 之前和之后添加了一些行为。
@my_decorator 语法用于将 my_decorator 函数应用于 say_hello 函数。这等效于调用 say_hello = my_decorator(say_hello)。
当我们调用 say_hello() 时,将调用 wrapper 函数而不是原始的 say_hello 函数。wrapper 函数在调用原始的 say_hello 函数之前和之后添加了一些行为。
以下是另一个带有参数的装饰器示例:
def repeat(num_times): def decorator_repeat(func): def wrapper_repeat(*args, **kwargs): for i in range(num_times): print('Iteration {} of {}'.format(i+1, num_times)) func(*args, **kwargs) return wrapper_repeat return decorator_repeat@repeat(num_times=3)def greet(name): print('Hello, {}'.format(name))# 调用装饰过的函数greet('Inspiration')
在这个示例中,repeat 函数是一个装饰器工厂,它返回一个装饰器函数 decorator_repeat。decorator_repeat 函数将一个函数 func 作为参数,并返回一个新函数 wrapper_repeat。wrapper_repeat 函数基于传递给 repeat 装饰器的 num_times 参数,多次调用原始的 func。
@repeat(num_times=3) 语法用于将 repeat 装饰器应用于 greet 函数。这等效于调用 greet = repeat(num_times=3)(greet)。
当我们调用 greet('John') 时,将调用 wrapper_repeat 函数而不是原始的 greet 函数。wrapper_repeat 函数根据传递给 repeat 装饰器的 num_times 参数,调用原始的 greet 函数三次。
联系客服