In Python
In Python, functions are first-class objects, just like strings, numbers, lists etc. This feature eliminates the need to write a function object in many cases. Any object with a __call__
method can be called using function-call syntax.
An example is this accumulator class (based on Paul Graham's study on programming language syntax and clarity):
class Accumulator(object): def __init__(self, n): self.n = n def __call__(self, x): self.n += x return self.nAn example of this in use (using the interactive interpreter):
>>> a = Accumulator(4)
>>> a(5)
9
>>> a(2)
11
>>> b = Accumulator(42)
>>> b(7)
49
A function object using a closure in Python 3:
def Accumulator(n): def inc(x): nonlocal n n += x return n return incRead more about this topic: Function Object