Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think your intuition is about right.</p> <p>Historically, callable objects (or what I've sometimes heard called "functors") have been used in the OO world to simulate closures. In C++ they're frequently indispensable.</p> <p>However, <code>__call__</code> has quite a bit of competition in the Python world:</p> <ul> <li>A regular named method, whose behavior can sometimes be a lot more easily deduced from the name. Can convert to a bound method, which can be called like a function.</li> <li>A closure, obtained by returning a function that's defined in a nested block.</li> <li>A lambda, which is a limited but quick way of making a closure.</li> <li>Generators and coroutines, whose bodies hold accumulated state much like a functor can.</li> </ul> <p>I'd say the time to use <code>__call__</code> is when you're not better served by one of the options above. Check the following criteria, perhaps:</p> <ul> <li>Your object has state.</li> <li>There is a clear "primary" behavior for your class that's kind of silly to name. E.g. if you find yourself writing <code>run()</code> or <code>doStuff()</code> or <code>go()</code> or the ever-popular and ever-redundant <code>doRun()</code>, you may have a candidate.</li> <li>Your object has state that exceeds what would be expected of a generator function.</li> <li>Your object wraps, emulates, or abstracts the concept of a function.</li> <li>Your object has other auxilliary methods that conceptually belong with your primary behavior.</li> </ul> <p>One example I like is UI command objects. Designed so that their primary task is to execute the comnand, but with extra methods to control their display as a menu item, for example, this seems to me to be the sort of thing you'd still want a callable object for.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload