是否可以将参数传递给装饰函数?

时间:2018-08-22 14:45:16

标签: python decorator

我写了下面的装饰器:

import time

def runtime(some_function):   
    def wrapper():
        start = time.time()        
        some_function()         
        runtime = time.time() - start   
        print(runtime)       
    return wrapper              

@runtime
def printing(upper_limit):
    for number in range(upper_limit):
        print(number)

printing(10)
printing(100)
printing(1000)
printing(10000)

我为什么得到:

  

TypeError:wrapper()接受0个位置参数,但给出了1个

运行代码时以及如何对其进行修复?

1 个答案:

答案 0 :(得分:2)

您需要使wrapper接受参数并将其传递给some_function。它还应返回some_function返回的值,以更通用。

def runtime(some_function):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = some_function(*args, **kwargs)
        runtime = time.time() - start
        print(runtime)
        return result
    return wrapper