我之前读过一个问题,询问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")
当我运行程序时,我得到以下异常:
Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\py\repeatable.py", line 24, in threeArgs.times(7, "one", two="rawr", three="foo") AttributeError: 'NoneType' object has no attribute 'times'
,所以我想这个装饰没有工作?我怎样才能解决这个问题?
这种方法似乎是不太习惯,少个简单你正在替换的那个。 – 2010-04-17 23:09:32