Very, Very Green Python User
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Wed Mar 15 22:34:02 EST 2006
hanumizzle at gmail.com a écrit :
> bruno at modulix wrote:
>
(snip)
>>You don't even need this to use callbacks. Remember, functions and
>>methods are objects, and other objects can be callable too...
>
> Eh?? I need an example.
Of callables ?
class FuncInDisguise(object):
def __init__(self, name):
self.name = name
def __call__(self, who):
return "Hello, %s, my name is %s" % (who, self.name)
hello_from_bruno = FuncInDisguise("bruno")
print hello_from_bruno("hanumizzle")
It's somewhat equivalent to a more functional :
def curry(fun, *args):
def _curried(*moreargs):
return fun(*(args + moreargs))
_curried.func_name = "curried(%s) of %r" % (", ".join(args), fun)
return _curried
def greeting(name, who):
return "Hello, %s, my name is %s" % (who, name)
hello_from_bruno2 = curry(greeting, "bruno")
print hello_from_bruno2("hanumizzle")
Now when it comes to callbacks, just pass around any callable with a
compatible signature, and this should Just Work(tm):
def test(callback):
result = callback('baaz')
print "in test, got: '%s'" % result
return result
class Foo(object):
def __init__(self, name):
self.name = name
def doit(self, arg):
return "%s %s" % (self.name, arg)
f = Foo('bar')
print test(f.doit)
print test(hello_from_bruno)
print test(hello_from_bruno2)
print test(FuncInDisguise)
print test(lambda n: "what should I do with %s ?" % n)
print test(lambda n: ("what should I do with %s ?" % n).split)
And why we're at it, why not have some fun calling the result of a
callback ?-)
print test(FuncInDisguise)('madman')
print test(lambda n: ("what should I do with %s ?" % n).split)()
HTH
More information about the Python-list
mailing list