Can't define __call__ within __init__?
Simon Brunning
simon at brunningonline.net
Wed Mar 10 08:27:31 EST 2010
On 10 March 2010 13:12, Neal Becker <ndbecker2 at gmail.com> wrote:
> Want to switch __call__ behavior. Why doesn't this work? What is the
> correct way to write this?
>
> class X (object):
> def __init__(self, i):
> if i == 0:
> def __call__ (self):
> return 0
> else:
> def __call_ (self):
> return 1
>
>
> x = X(0)
>
> x()
> TypeError: 'X' object is not callable
__call__ is in the __init__ method's local namespace - you need to
bind it to the class's namespace instead:
X.__call__ = __call__
But this probably isn't what you want either, since all instances of X
will share the same method.
What are you trying to do? In your simple example, you'd be much
better off with a single __call__ method. But you knew that.
--
Cheers,
Simon B.
More information about the Python-list
mailing list