Skip to main content
 首页 » 编程设计

python之不使用函数名的递归调用

2024年08月12日32落叶

正如您在下面的代码中看到的,如果删除了原始函数,使用函数名称的递归调用将失败。

有什么办法可以通过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)