dyn added methods dont know self?

Andrew Csillag drew.csillag at starmedia.net
Wed Feb 2 10:35:33 EST 2000


moonseeker at my-deja.com wrote:
> 
> Hi!
> 
> I want to add a method dynamically to an instance, how can I do this? I tried
> with exec '...' in self.__dict__, but this method doesn't know the instance
> reference 'self', so it would complain that it is called without an argument.
> Is there any other method to add a method dynamically?

You can't add a method directly to an instance unless you write a little
wrapper object to wrap self into it, i.e.

class BoundMethod:
    def __init__(self, otherSelf, func):
        self.func = func
        self.otherSelf = otherSelf

    def __call__(self, *args, **kw):
        return apply(self.func, (self.otherSelf,)+args, kw)

def methodIWillAdd(self):
    print self.boink

class WantToAddMethod:
    def __init__(self, boink):
        self.boink = boink

inst = WantToAddMethod('boinkVal')
inst.newMethod = BoundMethod(inst, methodIWillAdd)
inst.newMethod()

Running this prints boinkVal to the console.

Alternatively, you can add the function to the class (not the instance)
and it will get self automatically, but then each instance of the class
now has this new method too which may not be desirable.

Cheers,
Drew
-- 
print(lambda(q,p):'pmt:$%0.2f'%(q*p/(p-1)))((lambda(a,r,n),t:(a*r/
t,pow(1+r/t,n*12)))(map(input,('amt:','%rate:','years:')),1200.0))




More information about the Python-list mailing list