装饰器的真正用途是什么?

What is the real use of decorators?

我正在尝试了解装饰器在现实世界中的使用。

关于装饰器我们都知道是用来装饰函数的。 这意味着我们可以向现有函数添加一些额外的东西,但它可以通过使用其他简单函数来完成,我们也可以调用一个函数来调用另一个函数。那么为什么我们需要使用装饰器。

我已经尝试制作了两个程序

  1. 带装饰器

    def decor_result(result_as_argument):
     def new_function(marks):
         for i in marks:
                if i>= 75:
                    print("Congrats distiction",i)   
           else:
               result_as_argument(marks)
       return new_function
    
    @decor_result
    def result(marks):
       for i in marks:
           if i >= 35:
               pass
            else:
                print("Fail")
            break
        else:
            print("Pass")   
    
    result([79,65,55,78,12])
    
  2. 没有装饰器

    def result_distict(marks):
        for i in marks:
            if i>= 75:
                print("Congrats distiction",i)   
        else:
            result(marks)
    def result(marks):
        for i in marks:
            if i >= 35:
                pass
            else:
                print("Fail")
                break
        else:
            print("Pass")
    result_distict([79,65,55,78,12])
    result([79,65,55,78,12])
    

通过这样做,我开始知道不使用装饰器,它更加简化,我们可以自由使用我们想要的任何功能,而通过使用装饰器,我们不能使用旧功能那么为什么以及在哪里使用装饰器?

在你的例子中,没有必要做装饰器。当您尝试对一组函数实现特定行为时,您希望使用装饰器。例如,假设您要显示脚本中所有函数的执行时间。

解决方法1)你在各处加一小段代码来显示:

from time import time

def f1():
    t0 = time()
    # f1 body
    print("Execution time of f1: {}".format(time()-t0))

def f2():
    t0 = time()
    # f2 body
    print("Execution time of f2: {}".format(time()-t0))

如您所见,代码非常重复。如果您想更改此共享行为中的任何内容,则必须修改所有功能。这就是装饰器的用武之地。

2) 使用装饰器:

def timer(func):
    def wrapper(*args,**kwargs):
        t0 = time()
        res = func(*args,**kwargs)
        duration = time()-t0

        print("Execution time of {}: {} s".format(func.__name__, duration))
        return res

    return wrapper

@timer
def f1():
    # body of f1

@timer
def f2():
    # body of f2