Dynamic binding of class functions

gideon may gideon at computer.org
Thu Jun 21 02:20:27 EDT 2001


Hi,

I have the following problem. I would like to dynamically add methods
to existing instances of classes. I've succeeded creating a new function

on the fly and adding it to the dictionary of the class instance, but
when
I try to call the method through class.newmethod(), the method
doesn't receive the self paramater in the parameter list. I've tried the
following code :

def makefunc(r):
 func =        'def ' + r + '(self):\n'
 func = func + ' print "called ' + r +'"\n'
 func = func + ' print "dir = ", dir()\n'
 func = func + ' return "Done '  + r + '"\n'
 return func

class Device:
 def __init__(self):
  self.host = "localhost"
  r = 'xxxx'
  f = makefunc(r)
  print f
  exec f in self.__dict__

if __name__ == "__main__":
 d = Device()
 print dir(d)
 d.xxxx()

What am I doing wrong ?





More information about the Python-list mailing list