exec

Rolf Wester rolf.wester at ilt.fraunhofer.de
Thu Mar 1 08:07:15 EST 2012


Hi,

I would like to define methods using exec like this:

class A:
    def __init__(self):
        cmd = "def sqr(self, x):\n    return x**2\nself.sqr = sqr\n"
        exec cmd
a = A()
print a.sqr(a, 2)

This works, but I have to call sqr with a.sqr(a, 2), a.sqr(2) does not work
(TypeError: sqr() takes exactly 2 arguments (1 given)).

Is there a possibility to define methods using exec and getting normal behavior?

I would be very appreciative for any help.

With kind regards
Rolf Wester





More information about the Python-list mailing list