Re: __call__
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: __call__

From: Mike Meyer <mwm@mired.org>
Date: Sat May 28 2005 - 22:12:34 CEST

TK <merman@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@mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Received on Thu Sep 29 16:15:38 2005