Dynamic binding of class functions

Robert Roy rjroy at takingcontrol.com
Sun Jun 24 11:56:39 EDT 2001


On Thu, 21 Jun 2001 08:20:27 +0200, gideon may <gideon at computer.org>
wrote:


>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 ?
>
>
You need to use the new module to bind the method to the instance. The
following works.
Bob
########

import new
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
        setattr(self, r,
new.instancemethod(eval(r),self,self.__class__))# in self.__dict__

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





More information about the Python-list mailing list