I was just playing around with a python function that changes itself and couldn't avoid infinite recursion. At some point I made this:
def mitsos(a):
global mitsos
def takis(f):
def w(*args, **kargs):
ret = f(*args, **kargs)
return ret + 1
return w
mitsos = takis(mitsos)
return a
This unexpectedly worked. If i call mitsos(1) multiple times the result is always by 1 higher than the previous result. Why doesn't it fall in infinite recursion though?
Your original function is not recursive at all, less infinitely recursive. Function mitsos
creates another function takis
. Then it calls that function. The function takis
creates another function w
and returns it. The new function becomes the value of mitsos
, and the original mitsos
returns. Period.
The redefined function is one step-recursive, and it redefines mitsos
again. The new mitsos
is two-step recursive, etc. But none of them is infinitely recursive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.