I'm trying to do metaprogramming. I'm sure I've got this all wrong wrong wrong, but somehow my approach hasn't yet hit a brick wall.
Anyway, I'd like to dynamically add a method to an instance at instantiation time. Something like ###### In [71]: class quux(object): ....: def __init__(self,stuff): ....: template = "def foo(self,b): print b + %s" % stuff ....: exec(template) ....: self.bazz = foo ....: In [72]: q = quux(5) In [73]: q.bazz(4) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/tobis/PyNSol/<console> TypeError: foo() takes exactly 2 arguments (1 given) In [74]: q.bazz("not much",4) 9 ######## So the straightforward question is why, even though bazz is a method of class quux, it doesn't have that extra call parameter 'self'. Is this a problem? If I actually need a reference to self is it OK to do: In [76]: q.bazz(q,4) ? The more vague question is why do people despise 'exec', and how should I do this sort of thing instead? mt PS - any idea how to get past google's stupid formatting these days? I thought they were supposed to like python, but they just ignore leading blanks. -- http://mail.python.org/mailman/listinfo/python-list