[Tutor] definition question

Alan Gauld alan.gauld@blueyonder.co.uk
Sun Aug 3 12:51:14 EDT 2003


> I am writing a number of functions for my current project, and a
thought
> occured to me: Are they objects?

In Python they are objects. Python regards functions as
objects that can be passed around and that have attributes
and even methods.

>>> def foo():
...      'A silly function that does nothing'
...      print 'foo'
...
>>> foo.__doc__
A silly function that does nothing
>>> def bar(f,n):
...    for i in range(n): f()
...
>>> bar(foo,3)
foo
foo
foo
>>>

So we can pass foo as an object into bar, we can inspect its
doc string, and there are other attributes we could look at too.
In recent Pythons we can even subclass it:

class myFunc(foo):
   pass

Although how we would use that I'm struggling to think...

So yes a function is an object, but a special one in that it
is not instantiated from a class. BUT this is a very Pythonic
feature and in most languages a function is not an object.

In fact in Java, to do what we did with bar above you have to
define a class with a predetermined method (usually called
run or similar) and pass the class into bar:

>>> class doit:
...    def run(s)
...      print 'phony foo
...
>>> def bar2(c,n):
...   for i in range(n):
...     C().run()
...
>>> bar2(doit,3)
phony foo
phony foo
phony foo

Hopefully its clear that this is a cumbersome and restricted
way of doing things and treating functions as objects has
some big advantages. Significantly the purest of all OOP
languages, Smalltalk, also treats blocks of code as objects
to avoid just this kind of awkwardness.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld





More information about the Tutor mailing list