Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #80245
| Path | csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail |
|---|---|
| From | alex23 <wuwei23@gmail.com> |
| Newsgroups | comp.lang.python |
| Subject | Re: [Python-Dev] Dinamically set __call__ method |
| Date | Wed, 05 Nov 2014 15:28:43 +1000 |
| Organization | A noiseless patient Spider |
| Lines | 40 |
| Message-ID | <m3ccik$r48$1@dont-email.me> (permalink) |
| References | <CAF0TK51TKs+tw=u_rzrWVeSsDK7cOBt1Gcvq_izLfMObuDYNig@mail.gmail.com> <mailman.15460.1415125440.18130.python-list@python.org> |
| Mime-Version | 1.0 |
| Content-Type | text/plain; charset=ISO-8859-1; format=flowed |
| Content-Transfer-Encoding | 8bit |
| Injection-Date | Wed, 5 Nov 2014 05:28:53 +0000 (UTC) |
| Injection-Info | mx02.eternal-september.org; posting-host="f141bde4d1e4edae3516bb9f1d8e176c"; logging-data="27784"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18CqXhS6m6vgPG3+T5vNgq3" |
| User-Agent | Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.6.0 |
| In-Reply-To | <mailman.15460.1415125440.18130.python-list@python.org> |
| Cancel-Lock | sha1:JUGuFw1hmqTpZDpfweppy949CFM= |
| Xref | csiph.com comp.lang.python:80245 |
Show key headers only | View raw
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".
Given that special methods can only be replaced on the class and not the
instance, you could create a new version of the class within __init__
and assign it to the instance:
class A:
def __init__(self, call_method=None):
if call_method:
methods = {'__call__': call_method}
self.__class__ = type('Custom_A', (A,), )
def __call__(self):
return 'original'
>> a = A()
>> a()
"old"
>> b = A(lambda self: 'new')
>> b()
"new"
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Re: [Python-Dev] Dinamically set __call__ method Ethan Furman <ethan@stoneleaf.us> - 2014-11-04 10:23 -0800 Re: [Python-Dev] Dinamically set __call__ method alex23 <wuwei23@gmail.com> - 2014-11-05 15:28 +1000
csiph-web