Python(装饰器)

装饰器是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()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

在这个例子中,my_decorator 是一个装饰器,它接受一个函数 func 作为参数,然后返回一个新的函数 wrapper。在 wrapper 函数中,我们可以在调用原始函数前后执行一些额外的操作。通过在 say_hello 函数上添加 @my_decorator 注释,我们告诉 Python 在调用 say_hello 时应用 my_decorator 装饰器。

装饰器的灵活性在于它可以被组合使用,也就是说,你可以同时使用多个装饰器来修改函数的行为。例如:

def decorator1(func):
    def wrapper():
        print("Decorator 1 before")
        func()
        print("Decorator 1 after")
    return wrapper

def decorator2(func):
    def wrapper():
        print("Decorator 2 before")
        func()
        print("Decorator 2 after")
    return wrapper

@decorator1
@decorator2
def my_function():
    print("My Function")

my_function()
Decorator 1 before
Decorator 2 before
My Function
Decorator 2 after
Decorator 1 after

在这个例子中,my_function 被同时应用了 decorator1decorator2 装饰器,它们的执行顺序由下往上。运行 my_function 时,会按照装饰器的顺序依次执行各个包装函数。

总体来说,装饰器是 Python 中强大的工具,可以使代码更加模块化和可重用。它是理解一些高级框架和库中的重要概念之一。



posted @   做梦当财神  阅读(211)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示