Any way for a function to refer to itself?
Joshua Marshall
jmarshal at mathworks.com
Thu Feb 22 15:22:16 EST 2001
Joshua Marshall <jmarshal at mathworks.com> wrote:
> Lee, Rick <rickylee at americasm01.nt.com> wrote:
>> I can't find any other way for a function or method to refer to itself
>> than something like the following:
>> def foo():
>> myself = foo # only if foo is global
>> mydoc = myself.__doc__
>> myname = myself.__name__
>> So it can be done this way, but:
>> - only if the function name can actually be accessed from the current
>> name space
>> - if the function name changes, that first line inside this function
>> also has to change
>> Seems to me there should be a more "Pythonic" way of doing this. Is
>> there?
> It might be unpleasant, but you can do something like:
> def fib(f, x):
> if x < 2: return 1
> return f(f, x-1) + f(f, x-2)
> print fib(fib, 10)
And I guess if you don't like the idea of always having to pass your
function in to itself, you can wrap it:
def fib(x):
def _fib(f, x):
if x < 2: return 1
return f(f, x-1) + f(f, x-2)
return _fib(_fib, x)
print fib(10)
More information about the Python-list
mailing list