Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #21088

Re: exec

Date 2012-03-01 14:46 +0100
From Jean-Michel Pichavant <jeanmichel@sequans.com>
Subject Re: exec
References <4f4f7527$1@news.fhg.de>
Newsgroups comp.lang.python
Message-ID <mailman.320.1330609611.3037.python-list@python.org> (permalink)

Show all headers | View raw


Rolf Wester 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)).
>
> 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
>
>
>   
I'll try to ignore you are using the exec statement which is an error :o)

a.sqr(2) would have worked only if sqr was a *bound* method.

print a.sqr
<function sqr at 0x94ecd14>


to oppose to
print a.__init__
<bound method A.__init__ of <__main__.A instance at 0x948734c>>


You cannot dynamically bind a method, however you can do the following.

cmd = "def sqr(x):\n    return x**2\nself.sqr = sqr\n"



http://docs.python.org/reference/datamodel.html : <http://docs.python.org/reference/datamodel.html>
"It is also important to note that user-defined functions which are attributes of a class instance are not converted bound methods; this only happens when the function is an attribute of the class. "

JM

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

exec Rolf Wester <rolf.wester@ilt.fraunhofer.de> - 2012-03-01 14:07 +0100
  Re: exec Jean-Michel Pichavant <jeanmichel@sequans.com> - 2012-03-01 14:46 +0100
  Re: exec Arnaud Delobelle <arnodel@gmail.com> - 2012-03-01 14:13 +0000
  Re: exec Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-03-01 14:21 +0000
  Re: exec Rolf Wester <rolf.wester@ilt.fraunhofer.de> - 2012-03-01 16:58 +0100
    Re: exec Michael Ströder <michael@stroeder.com> - 2012-03-01 17:26 +0100
    Re: exec Peter Otten <__peter__@web.de> - 2012-03-01 18:14 +0100
      Re: exec Rolf Wester <rolf.wester@ilt.fraunhofer.de> - 2012-03-01 18:23 +0100
    Re: exec Peter Otten <__peter__@web.de> - 2012-03-02 08:26 +0100

csiph-web