Python 在运行时向函数对象添加方法

Python 在运行时向函数对象添加方法,python,function,decorator,Python,Function,Decorator,我之前读过一个问题,问Python中是否有times方法,该方法允许一个函数连续调用n次 每个人都建议为范围(n)内的uu:foo()编写,但我想尝试使用函数装饰器编写不同的解决方案 以下是我所拥有的: def times(self, n, *args, **kwargs): for _ in range(n): self.__call__(*args, **kwargs) import new def repeatable(func): func.times

我之前读过一个问题,问Python中是否有
times
方法,该方法允许一个函数连续调用n次

每个人都建议为范围(n)内的uu: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' 回溯(最近一次呼叫最后一次): 文件“”,第244行,在run_nodebug中 文件“C:\py\repeatable.py”,第24行,在 三个参数的次数(7,“1”,2=“rawr”,3=“foo”) AttributeError:“非类型”对象没有属性“时间”
那么我猜装修工没有工作?如何修复此问题?

您的装饰程序应返回函数对象:

def repeatable(func):
    func.times = new.instancemethod(times, func, func.__class__)
    return func
现在它不返回任何值,所以实际上在None中更改了三个参数

这是因为:

@decorator
def func(...):
    ...
与以下内容大致相同:

def func(...):
    ....
func = decorator(func)

您的
可重复的
装饰程序末尾缺少一条
return func
语句。

您是否考虑过不将其添加到特定函数中,而是允许其与任何函数一起使用

def times(n, func, *args, **kwds):
  return [func(*args, **kwds) for _ in xrange(n)]
(我正在返回一个返回值列表,但您可以编写它来忽略它们,类似于您在问题中遇到的for循环。)

然后,在您的版本中,使用:

threeArgs.times(7, "one", two="rawr", three="foo")
而是使用:

times(7, threeArgs, "one", two="rawr", three="foo")

太棒了,我想我应该想到。。。哦,好吧,谢谢你的帮助。这个方法似乎没有你要替换的那个那么惯用,也不那么简单。