[Tutor] Function object

Emile van Sebille emile at fenx.com
Wed Aug 25 19:56:27 CEST 2010


On 8/25/2010 9:56 AM Daniel said...
> Hello again, seems like in my journey to learn Python I have stumbled into
> 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? I'm currently reading Think python, but the book is not
> clear for me. Python is my first programming language.
> Please, can you give me some examples and if it is possible can you explain
> in a more beginner orientated way?

Generally speaking, everything in python is an object.  As such, objects 
have methods and attributes.  At a certain level for certain projects, 
manipulating code objects helps solve problems.

Here's a simple example.

ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit 
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> def test(ii): print "my name is %s" % ii.func_name
...
 >>> def test1(ii): print "my name is %s" % ii.func_name
...
 >>> def test2(ii): print "double ii is %s-%s" % (ii,ii)
...
 >>> for funcobj in (test1,test2): funcobj('spam')
...
single ii is spam
double ii is spam-spam
 >>>for funcobj in (test1,test2): test(funcobj)
...
my name is test1
my name is test2

Once defined, code is an object.  try dir(test) on the above.

HTH,

Emile



More information about the Tutor mailing list