在Python中,装饰器是一种特殊类型的函数,它允许你动态地修改其他函数的行为。装饰器通常用于在不修改原函数代码的情况下,扩展或修改函数的功能。下面是一个简单的装饰器函数的示例:
def my_decorator(func):
def wrapper(*args, kwargs):
print("Before calling the function")
result = func(*args, kwargs)
print("After calling the function")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
在这个例子中,`my_decorator` 是一个装饰器函数,它接受一个函数 `func` 作为参数,并返回一个新的函数 `wrapper`。在 `wrapper` 函数中,我们可以在调用原始函数 `func` 之前和之后添加额外的逻辑。通过在 `say_hello` 函数上方添加 `@my_decorator` 语法,我们将 `say_hello` 函数传递给 `my_decorator` 装饰器函数,并将返回的新函数赋值给 `say_hello`,这样 `say_hello` 函数就被装饰了。当我们调用 `say_hello` 函数时,实际上会调用装饰后的 `wrapper` 函数,从而在打印 "Hello!" 之前和之后分别打印 "Before calling the function" 和 "After calling the function"。