我写了下面的装饰器:
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个
运行代码时以及如何对其进行修复?
答案 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