Functors

Un functor (function object) es una instancia que puede ser invocada. Esto es gracias al método especial __call__:


In [3]:
class Mapper(object):
    def __init__(self, func):
        self.f = func
        
    def __call__(self, data):
        return map(self.f, data)
    
square = Mapper(lambda x:x**2)
square(range(6))


Out[3]:
[0, 1, 4, 9, 16, 25]

Un decorador por medio de un functor:


In [8]:
class trace(object):
    def __init__(self, func):
        self.func = func
        
    def __call__(self, *args, **kargs):
        print("-- before calling to {}".format(self.func))
        retval = self.func(*args, **kargs)
        print("-- after calling to {}".format(self.func))

@trace
def bob_say(what):
    print("Bob says '{}'".format(what))
    
bob_say("hello")


-- before calling to <function bob_say at 0x7f9b886d0938>
Bob says 'hello'
-- after calling to <function bob_say at 0x7f9b886d0938>