
在 Python 中,装饰器(decorator)是一种函数,用于在不修改原函数代码的情况下,扩展或修改函数的行为。装饰器通常用于日志记录、权限验证、缓存等场景。装饰器本质上是一个高阶函数,它接受一个函数作为参数并返回一个新的函数。
以下是一个简单的装饰器示例:
def my_decorator(func):def wrapper():print("在函数调用之前触发")
func()
print("在函数调用之后触发")
return wrapper
@my_decoratordef say_hello():print("Hello!")
say_hello()在这个示例中:
my_decorator 是一个装饰器函数,它接受一个函数 func 作为参数,并定义了一个内部函数 wrapper 来包裹 func。wrapper 函数在调用 func 之前和之后添加了一些操作,然后调用 func。@my_decorator 语法糖用于将 say_hello 函数传递给 my_decorator,相当于 say_hello = my_decorator(say_hello)。say_hello() 时,会执行 wrapper 函数,从而在 say_hello 函数前后添加了额外的行为。输出结果如下:
在函数调用之前触发
Hello!
在函数调用之后触发装饰器可以带参数,可以用于类方法,还可以将多个装饰器叠加使用。以下是一个带参数的装饰器示例:
def repeat(num_times):def decorator_repeat(func):def wrapper(*args, **kwargs):for _ inrange(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times=3)def greet(name):print(f"Hello, {name}!")
greet("Alice")在这个示例中,我们定义了一个 repeat 装饰器,它接受一个参数 num_times,用于指定函数应被调用的次数。
输出结果如下:
Hello, Alice!
Hello, Alice!
Hello, Alice!原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。