exec

Arnaud Delobelle arnodel at gmail.com
Thu Mar 1 09:13:39 EST 2012


On 1 March 2012 13:07, Rolf Wester <rolf.wester at ilt.fraunhofer.de> wrote:
> 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)).

I'm curious to know your motivation for doing this.

-- 
Arnaud



More information about the Python-list mailing list