Search code examples
pythonmonkeypatchingsetattr

How do you bind methods to objects in python during runtime?


I want to add a method to an object during runtime as thus.

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)

But it seems that setattr does not bind the method to the object. Is it possible to do this?


Solution

  • You can use MethodType from types module:

    import types
    
    obj.f = types.MethodType(f, obj)    
    obj.f()
    

    But are you really need this? Look for decorators (for example), it's more elegant way to add needed functionality to class.