Python中的装饰器是什么?

Python网络爬虫与数据挖掘

共 4381字,需浏览 9分钟

 · 2024-04-11

引言

在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作为参数,并返回一个新的函数wrapperwrapper函数中加入了在func执行前后需要执行的代码。通过@my_decorator,我们将这个装饰器应用到了say_hello函数上。

装饰器中传递参数

如果我们的函数有参数怎么办?装饰器也能很好地处理这种情况。看下面的例子:

      
      def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper

@my_decorator
def say(message):
    print(message)

say("Hello with argument!")

这段代码中,wrapper函数使用了*args**kwargs来接受任意数量和类型的参数,这使得装饰器变得更加灵活。

使用多个装饰器

Python也支持给一个函数同时使用多个装饰器,如下所示:

      
      def decorator_one(func):
    def wrapper():
        print("Decorator one!")
        func()
    return wrapper

def decorator_two(func):
    def wrapper():
        print("Decorator two!")
        func()
    return wrapper

@decorator_one
@decorator_two
def say_hello():
    print("Hello!")

say_hello()

当使用多个装饰器时,它们的执行顺序是从近到远,即先decorator_twodecorator_one

实例子: 计算函数执行所需时间

现在 通过一个更实际的例子来进一步理解装饰器: 假设我们要编写一个装饰器,用于计算任何函数执行所需的时间。 这在性能测试时非常有用。

        
        import time

# 创建一个装饰器,它会计算并打印函数执行所需的时间
def time_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()  # 记录函数开始执行的时间
        result = func(*args, **kwargs)  # 执行函数
        end_time = time.time()  # 记录函数执行完成的时间
        print(f"{func.__name__} took {end_time - start_time} seconds to run.")
        return result
    return wrapper

# 使用装饰器
@time_decorator
def long_running_function(number):
    sum = 0
    for i in range(number):
        sum += i
    return sum

# 调用函数
print(long_running_function(1000000))

在这个例子中,我们首先定义了一个名为 time_decorator 的装饰器。 这个装饰器接受一个函数 func 作为参数,并返回一个新的函数 wrapper wrapper 函数会记录被装饰的函数执行前后的时间,从而计算出函数执行所需的总时间,并打印出来。

然后,我们创建了一个long_running_function函数,它接受一个参数并执行一个简单的累加操作。通过在这个函数前面添加@time_decorator,我们就把装饰器应用到了long_running_function上。

当我们调用long_running_function(1000000)时,装饰器会自动计算并打印出这个函数执行所需的时间。这样,我们就可以很容易地监控任何函数的性能了。

总结

装饰器是Python中一种非常强大的工具,它能够帮助我们以非常优雅的方式增强函数的功能,而不需要修改函数本身的代码。

加我微信,送你 一份Python入门全套电子书。 微信: lzjun567 (备注: 资料)

浏览 3
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报