你如何在运行时将方法绑定到 python 中的对象?

Irv*_*van 2 python monkeypatching setattr

我想在运行时向对象添加一个方法。

class C(object):
  def __init__(self, value)
    self.value = value

obj = C('test')

def f(self):
  print self.value

setattr(obj, 'f', f)
obj.f()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)

但似乎 setattr 并没有将方法绑定到对象。是否有可能做到这一点?

Mik*_*mov 5

您可以使用MethodTypefrom types模块:

import types

obj.f = types.MethodType(f, obj)    
obj.f()
Run Code Online (Sandbox Code Playgroud)

但是你真的需要这个吗?寻找装饰器(例如),这是向类添加所需功能的更优雅的方式。