Jump to content

Callable object

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Anarchyte (talk | contribs) at 13:02, 19 May 2017 (Added {{refimprove}} tag to article (TW)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A callable object, in computer programming, is any object that can be called like a function.

In different languages

In C++

std::function is a template class that can hold any callable object that matches its signature.

In C#

In PHP

PHP 5.3+ has first-class functions that can be used e.g. as parameter to the usort() function:

$a = array(3, 1, 4);
usort($a, function ($x, $y) { return $x - $y; });

It is also possible in PHP 5.3+ to make objects invokable by adding a magic __invoke() method to their class:[1]

class Minus {
    public function __invoke($x, $y) { return $x - $y; }
}

$a = array(3, 1, 4);
usort($a, new Minus());

In Python

In Python any object with a __call__() method can be called using function-call syntax.

class Accumulator(object):
    def __init__(self, n):
        self.n = n

    def __call__(self, x):
        self.n += x
        return self.n

References