newbie question, when __call__ method is used?

C

chenyu

Hi everyone,
I have read other's code, and found it contains the __call__. But I
don't know when its code will be executed.
From the Python manual, I know it is built-in function and is a
callback function. But the manual doesn't contain any simple example.

Could you give me an simple example to explain when its code will be
executed?



Thank you for your attention.
kind regards/chenyu
 
K

KefX

I have read other's code, and found it contains the __call__. But I
don't know when its code will be executed.

It will be executed when a class instance is executed as a function.

For example:
foobar = MyClass()
foobar(2)

This is the same as:
foobar = MyClass()
foobar.__call__(2)

One way of looking at it is that it's simple shorthand, but there's also
another advantage (which is the real reason it's there): it turns your class
instance into a 'callable', that is, almost anything that requires a function
can also take your class instance (in general).

- Kef
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top