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)
但似乎 setattr 并没有将方法绑定到对象。是否有可能做到这一点?
您可以使用MethodTypefrom types模块:
import types
obj.f = types.MethodType(f, obj)    
obj.f()
但是你真的需要这个吗?寻找装饰器(例如),这是向类添加所需功能的更优雅的方式。
| 归档时间: | 
 | 
| 查看次数: | 1350 次 | 
| 最近记录: |