【发布时间】:2015-09-03 10:48:06
【问题描述】:
我正在尝试编写 python 装饰器,但在理解内部包装器如何接受参数时遇到了问题。我这里有:
import time
def timing_function(some_function):
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run: " + str((t2-t1)) + "\n"
return wrapper
@timing_function
def my_function(x):
return x * x
my_function(6)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-fe2786a2753c> in <module>()
----> 1 my_function(6)
TypeError: wrapper() takes no arguments (1 given)
与示例略有不同:
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run the function: " + str((t2-t1)) + "\n"
return wrapper
@timing_function
def my_function():
num_list = []
for x in (range(0,10000)):
num_list.append(x)
return "\nSum of all the numbers: " +str((sum(num_list)))
print my_function()
Time it took to run the function: 0.0
似乎问题出在“x”参数上。我尝试提供包装器 *args,但它也不起作用。我的问题是
在这个简单的包装器中允许参数的正确方法是什么?谢谢
为什么我看到的所有装饰器示例总是有一个内部函数,你不能把装饰器写成一个函数吗?
谢谢
【问题讨论】:
-
在你的包装签名中使用
*args,**kwargs,所以def wrapper()变成def wrapper(*args, **kwargs)。这样,您可以在任何函数或方法上使用装饰器。
标签: python decorator python-decorators