__call__

Mike Meyer mwm at mired.org
Sat May 28 16:12:34 EDT 2005


TK <merman at o2online.de> writes:
> Simon Percivall wrote:
>> Look at http://docs.python.org/ref/callable-types.html
>>
>>>>>class Test(object):
>> ...     def __call__(self):
>> ...         print "the instance was called"
>> ...
>>
>>>>>t = Test()
>>>>>t()
>> the instance was called
>> Is this what you wanted?
>
> Sorry but it does not work. Here's my code:
>
>  >>> class Test(object):
> ...     def __call__(self):
> ...         print 'Hi'
> ...
>  >>> Test()
> <__main__.Test object at 0x3e6d0>

Test() invokes the class, which returns an instance of the class.

Look back at what Simon did. He stored the value returned by Test() as
t, then called t with "t()". That's what __call__ is - the routine
invoked when an instance of a class is invoked as a callable object.

To change what happens when the class is invoked as a callable object,
you need to fool with metaclasses.

It might help if you told us what you really wanted to do with this
construct.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list