在Python中装饰实例方法

Koo*_*obz 3 python django class decorator instance

这是我要做的事情的要点.我有一个对象列表,我知道他们有一个实例方法,如下所示:

def render(self, name, value, attrs)
   # Renders a widget...
Run Code Online (Sandbox Code Playgroud)

我想(essentialy)在运行时装饰这些函数,因为我正在迭代对象列表.这样他们的渲染函数就变成了:

def render(self, name, value, attrs)
   self.attrs=attrs
   # Renders a widget...
Run Code Online (Sandbox Code Playgroud)

两个警告:

  1. 渲染函数是django的一部分.我不能把装饰器放在他们的库中(我可以,但是我必须维护和迁移这个改变).
  2. 这是一个实例方法.

这里有一个例子:http: //wiki.python.org/moin/PythonDecoratorLibrary

演示如何向类添加新的实例方法.这里的区别是我想记住那个attrs参数后我想要落到原来的方法.

Ale*_*lli 7

def decorate_method(f):
  def wrapper(self, name, value, attrs):
    self.attrs = attrs
    return f(self, name, value, attrs)
  return wrapper

def decorate_class(c):
  for n in dir(c):
    f = getattr(c, n)
    if hasattr(f, 'im_func'):
      setattr(c, n, decorate_method(f.im_func))
Run Code Online (Sandbox Code Playgroud)

您可能需要一些其他测试来跳过具有不同签名的方法,但除此之外,decorate_class(whatever)应该在任何给定的类上执行您想要的操作whatever.

  • (最近我在你发布的另一个代码片段中发现了一个拼写错误,http://stackoverflow.com/questions/1653500/permutations-of-a-given-set-of-numbers/1653618#1653618.我必须说,我自己通常如果没有先在解释器中测试代码,就不会有足够的信心发布代码:) (2认同)