【发布时间】:2010-04-17 21:11:31
【问题描述】:
我之前读过一个问题,询问 Python 中是否有 times 方法,该方法允许连续调用函数 n 次。
每个人都建议for _ in range(n): foo(),但我想尝试使用函数装饰器编写不同的解决方案。
这是我所拥有的:
def times(self, n, *args, **kwargs):
for _ in range(n):
self.__call__(*args, **kwargs)
import new
def repeatable(func):
func.times = new.instancemethod(times, func, func.__class__)
@repeatable
def threeArgs(one, two, three):
print one, two, three
threeArgs.times(7, "one", two="rawr", three="foo")
当我运行程序时,我得到以下异常:
回溯(最近一次通话最后): 文件“”,第 244 行,在 run_nodebug 文件“C:\py\repeatable.py”,第 24 行,在 threeArgs.times(7, "one", two="rawr", three="foo") AttributeError:“NoneType”对象没有属性“次”所以我想装饰器没有工作?我该如何解决这个问题?
【问题讨论】:
-
与您要替换的方法相比,这种方法似乎不那么惯用和简单。