正如您在下面的代码中看到的,如果删除原始函数,使用函数名称的递归调用将会失败。
是否有任何方法可以通过诸如 this
或 self
之类的方式在其自身主体中引用该函数?
>>> def count_down(cur_count):
... print(cur_count)
... cur_count -= 1
... if cur_count > 0:
... count_down(cur_count)
... else:
... print('Ignition!')
...
>>> count_down(3)
3
2
1
Ignition!
>>> zaehle_runter = count_down
>>> zaehle_runter(2)
2
1
Ignition!
>>> del count_down
>>> zaehle_runter(2)
2
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 5, in count_down
NameError: name 'count_down' is not defined
最佳答案
当您递归调用函数时,会在(全局)范围内搜索函数名称。
由于该名称现已删除,因此无法找到。
要解决此问题,您可以创建一个执行递归工作的内部函数。这使得您的递归函数不受此删除的影响,因为它不再递归,而只是调用内部递归函数
def count_down(cur_count):
def internal_count_down(cur_count):
cur_count -= 1
if cur_count > 0:
internal_count_down(cur_count)
else:
print('Ignition!')
internal_count_down(cur_count)
关于python - 不使用函数名称的递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58773416/