dyn added methods dont know self?

Christian Tismer tismer at tismer.com
Wed Feb 2 10:26:44 EST 2000


Andrew Csillag wrote:
> 
> 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.

...
> 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.

Even weirder but shorter, you can dynamically insert the
method into the class, then create your bound instance
and save it away, and then delete the class' method again.

>>> class klass:
... 	pass
... #nothing there
... 
>>> inst = klass()
>>> 
>>> def fake(self, n):
... 	self.number = n
... 	
>>> klass.fake = fake
>>> meth = inst.fake
>>> del klass.fake
>>> meth(3)
>>> inst.number
3
>>> inst2=klass()
>>> inst2.fake
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: fake
>>>

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Düppelstr. 31                :    *Starship* http://starship.python.net
12163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home




More information about the Python-list mailing list