Python装饰器(不带参/带参)

普通装饰器示例

普通装饰器通常用于在不修改函数签名的情况下增强函数功能。

复制代码
# 定义一个普通装饰器
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

# 使用装饰器
@my_decorator
def say_hello():
    print("Hello!")

# 调用被装饰的函数
say_hello()
复制代码

 

在这个例子中,my_decorator 是一个装饰器,它接收一个函数 func 作为参数,并返回一个新的函数 wrapper。wrapper 函数在原有函数执行前后添加了一些额外的操作。使用 @my_decorator 语法可以将这个装饰器应用于 say_hello 函数。

带参数的装饰器示例

带参数的装饰器稍微复杂一些,因为它需要在装饰器外部接收参数。

复制代码
# 定义一个带参数的装饰器
def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(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("World")
复制代码

 

在这个例子中,repeat 是一个带参数的装饰器工厂,它接收一个参数 num_times。然后返回一个装饰器 decorator_repeat,这个装饰器再返回一个包装函数 wrapperwrapper 函数根据 num_times 参数决定原函数 func 被调用的次数。

带参数的装饰器通常用于需要定制装饰器行为的场景。通过这种方式,你可以在不修改装饰器内部逻辑的情况下,通过参数传递来改变装饰器的行为。

 
posted @   你的小可爱吖  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示