How to refer to the function object itself in the function per se?

James Stroud jstroud at ucla.edu
Sat Mar 11 17:51:03 EST 2006


Sullivan WxPyQtKinter wrote:
> I am sorry but you misunderstood my idea.
> What I want is a generalized method to print out the function name, or
> refer to the name of a function. If I use f.__name__, I think I should
> just use print "f" to save my keyboard. What I expect is using a
> method, or attribute, or another function to get the name of a
> function.

Not exactly:

py> def f():
...   print 'this is function f'
...
py> g = f
py>
py> print g.__name__
f

You might be confusing the idea of a name with the idea of a reference. 
It really doesn't matter what you name a function. As long as you have a 
reference to a function, or 'callable', you can call it.

py> g()
this is function f

You can even create a reference to a function and call that reference in 
the function after the function is defined:

py> def f(start, end):
...   if start >= end:
...     print 'start is end', start
...   else:
...     g(start+1, end)
...   print 'leaving function where start is', start
...
py> g = f
py> f(1,5)
start is end 5
leaving function where start is 5
leaving function where start is 4
leaving function where start is 3
leaving function where start is 2
leaving function where start is 1

But beware re-binding a name in such circumstances:

py> def g(*args):
...   print 'g rebound! args are', args
...
py> f(1,5)
g rebound! args are (2, 5)
leaving function where start is 1

I hope this clears things up.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list