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

2024-04-29 01:15:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图了解装饰师在现实世界中的用法。

来装饰我们都知道,它是用来装饰功能。 这意味着我们可以在现有的函数中添加一些额外的东西,但也可以通过使用其他简单的函数来完成,我们也可以调用一个函数来调用另一个函数。所以我们为什么要用装饰工。你知道吗

我已经试过做两个程序了

  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])
    

通过这样做,我知道不使用decorators,它会更加简化,我们可以自由地使用任何我们想要的函数,通过使用decorators,我们不能使用旧函数,那么为什么要使用decorator以及在何处使用decorator呢?


Tags: 函数innewforifdefas装饰
1条回答
网友
1楼 · 发布于 2024-04-29 01:15:53

在你的例子中,做一个装饰师是没有必要的。当您试图实现一组函数的特定行为时,需要使用装饰器。例如,假设您试图显示脚本中所有函数的执行时间。你知道吗

解决方案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

相关问题 更多 >