Add method to class

Jeremy Lowery jslowery at hotmail.com
Mon Dec 3 03:31:22 EST 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' % (self.name, x)
... '''
>>> ns = {}
>>> cbyte = compile(csrc, '<string>', 'exec')
>>> exec cbyte in {}, ns
>>> Spaminator.foo = new.instancemethod(ns['foo'], mySpam, Spaminator)
>>> mySpam.name = 'The Circus'
>>> mySpam.foo('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
object?

Jeremy







More information about the Python-list mailing list