[Tutor] Function object

Alan Gauld alan.gauld at btinternet.com
Wed Aug 25 20:44:05 CEST 2010


"Daniel" <asmosis.asterix at gmail.com> wrote

> another problem regarding understanding a concept- function object. 
> As I
> said, I do not understand what a function object is, what it does, 
> and what
> can I do with it?

You are actually using them all the time.
Every function in Python is a function object.
You can execute the function by putting parenthesesc after its 
name(filled
with any required arguments)

def foo(): return None

defines a function object called foo that does nothing but return 
None.

We can rewrite that using the lambda operator which returns function
objects with no name:

foo = lambda : None

This assigns an anonymous function object to a variable foo - thus 
giving
it a name, just like any other variable.

In both cases we can now call the function with:

foo()

The advantage of treating functions as objects is that we can store 
them
and then call them later. This is the basis of event driven 
programming
and GUIs. It also allows us to easily build reconfigurable dynamic 
logic
into applications - just by changing the order in which functions are 
called.

It also allows us to create functions which return functions as their 
output,
but this is getting into deeper water, so I'll ignore that for now! 
:-)

You will find a slightly different explanation in the Functional 
Programming
topic of my tutorial

HTH
-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list