[英]Recursive calls without using function's name
如您在下面的代碼中所見,如果刪除原始 function,則使用函數名稱的遞歸調用將失敗。
有什么方法可以通過this
或self
在自己的身體中引用 function 嗎?
>>> 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
當您遞歸調用 function 時,將在(全局)scope 中搜索 function 名稱。
由於該名稱現已被刪除,因此無法找到。
要解決此問題,您可以創建一個執行遞歸工作的內部 function。 這使您的遞歸 function 不受此刪除的影響,因為它不再遞歸,而只是調用內部遞歸 function
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.