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


Groups > comp.lang.python > #80218

Re: [Python-Dev] Dinamically set __call__ method

References <CAF0TK51TKs+tw=u_rzrWVeSsDK7cOBt1Gcvq_izLfMObuDYNig@mail.gmail.com> <545919B6.7040007@stoneleaf.us>
From Roberto Martínez <robertomartinezp@gmail.com>
Date 2014-11-04 20:01 +0100
Subject Re: [Python-Dev] Dinamically set __call__ method
Newsgroups comp.lang.python
Message-ID <mailman.15463.1415127726.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

Yikes, I didn't realize the difference in inheritance.

The thing with this is tricky. I need the change in the instance, not in
the class, because I have multiple instances and all of them must have
different implementations of __call__.

The workaround of calling a different method inside __call__ is not valid
for my case because I want to change the *signature* of the function also
-for introspection reasons.

Thank you all.

Best regards,
Roberto

(Ethan, sorry for posting to python-dev, I thought that it was an
implementation detail of CPython 3.X)

On Tue, Nov 4, 2014 at 7:23 PM, Ethan Furman <ethan@stoneleaf.us> wrote:

> This list is for the development _of_ Python, not development _with_
> Python.
>
> Try asking on Python List.
>
> (forwarding...)
>
>
> On 11/04/2014 08:52 AM, Roberto Martínez wrote:
>
>>
>> I am trying to replace dinamically the __call__ method of an object using
>> setattr.
>> Example:
>>
>> $ cat testcall.py
>> class A:
>>      def __init__(self):
>>          setattr(self, '__call__', self.newcall)
>>
>>      def __call__(self):
>>          print("OLD")
>>
>>      def newcall(self):
>>          print("NEW")
>>
>> a=A()
>> a()
>>
>> I expect to get "NEW" instead of "OLD", but in Python 3.4 I get "OLD".
>>
>> $ python2.7 testcall.py
>> NEW
>> $ python3.4 testcall.py
>> OLD
>>
>> I have a few questions:
>>
>> - Is this an expected behavior?
>> - Is possible to replace __call__ dinamically in Python 3? How?
>>
>
> In 2.7 that would be a classic class, about which I know little.
>
> In 3.x you have a new class, one which inherits from 'object'.  When you
> replace __call__ you need to replace it the class, not on the instance:
>
>   setattr(__self__.__class__, self.newcall)
>
> --
> ~Ethan~
>

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


Thread

Re: [Python-Dev] Dinamically set __call__ method Roberto Martínez <robertomartinezp@gmail.com> - 2014-11-04 20:01 +0100
  Re: [Python-Dev] Dinamically set __call__ method Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-11-07 15:18 +1100

csiph-web