what is a function object?

zakons at eccelerate.com zakons at eccelerate.com
Wed Nov 10 09:22:52 EST 1999

  Michael Hudson <mwh21 at cam.ac.uk> wrote:

> it doesn't know a priori that the name "foo" is bound to a
> function. So it looks the name "foo" up, and assuming it finds
> something, attempts to call it with argument x. "Attempting to call
> it" goes something like:
> if type(foo) is types.MethodType:
>      apply(foo.im_func,(foo.im_self,x))
> elif type(foo) is types.FunctionType:
>      apply(foo,(x,))
> elif hasattr(foo,'__call__'):
>      apply(foo.__call__,(x,))

Thanks Michael. Your comment on the __call__ builtin method keyed me
into Mark Lutz's index to Programming in Python. Buried in the way
back on page 747, Closures in Python, he describes a class called
'counter' which implements __call__. What this does is make 'counter'
both an object and a method! I believe this is what it means when folks
say "functions are first class objects in python".

The real question is still "OK, so why would I want to make a method
(function) a full blown class (object)?" It seems like this makes sense
when there is some desired side effect every time the method is called.
(Is there a recognized pattern for this type of behavior?)


Sent via Deja.com http://www.deja.com/
Before you buy.

More information about the Python-list mailing list