Can't define __call__ within __init__?

Steve Howell showell30 at yahoo.com
Thu Mar 11 11:20:14 EST 2010


On Mar 10, 7:18 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Wed, 10 Mar 2010 08:12:14 -0500, Neal Becker 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
>
> Others have already pointed out that there are two reasons that won't
> work:
>
> (1) you define __call__ as a local variable of the __init__ method which
> then disappears as soon as the __init__ method completes; and
>
> (2) special methods like __call__ are only called on the class, not the
> instance, so you can't give each instance its own method.
>

Are you sure about that?  This program prints 1, 2, 1, 2.

    class Foo:
        def __init__(self, a):
            if a == 1:
                self.__call__ = lambda: 1
            else:
                self.__call__ = lambda: 2

    foo1 = Foo(1)
    print foo1()

    foo2 = Foo(2)
    print foo2()

    print foo1()
    print foo2()

See here:

http://docs.python.org/reference/datamodel.html

Class instances
    Class instances are described below. Class instances are callable
only when the class has a __call__() method; x(arguments) is a
shorthand for x.__call__(arguments).



More information about the Python-list mailing list