Add method to class

Jeremy Lowery jslowery at
Mon Dec 3 09:31:22 CET 2001

Hello all,

I've been playing with a system that dynamically adds methods to classes,
and editing them, etc. I've found the following code works, but it has
several drawbacks.

>>> class Spaminator:
...  pass
>>> mySpam = Spaminator()
>>> csrc = \
... '''
... def foo(self, x):
...  print '%s spams %s' % (, x)
... '''
>>> ns = {}
>>> cbyte = compile(csrc, '<string>', 'exec')
>>> exec cbyte in {}, ns
>>> = new.instancemethod(ns['foo'], mySpam, Spaminator)
>>> = 'The Circus'
>>>'I hate perl!')
The Circus spams I hate perl!

The main problems with this is that you have to put the function definition
code inside the string. Would there be a way to just have the string as the
function body and programmaticly add the arguments to construct the function


More information about the Python-list mailing list