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 @ 2019-03-08 09:05  做梦当财神  阅读(205)  评论(0编辑  收藏  举报