Adding and modifying methods at run-time

Thomas Weholt 2002 at weholt.org
Fri Apr 30 17:03:30 EDT 2004


Hi,

I want to add methods to a class instance at run-time based on a base
method, but modify one of the existing ( or add if possible ) params of the
base method. Say a class like this :


class A:
  def __init__(self):
    self.obj1() # some dummy object having a name attribute
    self.obj2() # some dummy object having a name attribute
  def __method1__(self, param1, param2, param3 = None):
        # use some property on param3 in some operations
  def addNewMethod(self, param1, new_obj):
       new_func = copy.copy(self.__method1__)
       # modify a copy of self.__method1__ and change the param3 to point
new_obj
       # and add the method
       setattr(self, 'method4%s' % new_obj.name, new_func)

use the class like so :

a = A()
a.addNewMethod(1, a.obj1)
# use new dynamically method
a.method4obj1(1,2) # now the third param with a default is set to point to
obj1 instead of None

I'm crashing at the copy-method in addNewMethod. It crashes with the
exception "TypeError: function() takes at least 2 arguments (0 given)". This
is deep inside the copy-module.

Any hints or clues?

Best regards,
Thomas





More information about the Python-list mailing list