Ede*_*row -5 python memory function python-3.x
在我的脚本中,我有四个功能如下:
def function_four():
# Does Stuff
function_one()
def function_three():
# Does Stuff
function_two()
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
function_three()
elif usr_input == '2':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
function_four()
elif usr_input == '2':
function_three()
elif usr_input == '3':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
Run Code Online (Sandbox Code Playgroud)
我需要知道这是否会导致我认为会出现的问题:函数永远不会关闭,导致大量的打开函数(可能是浪费的内存和最终的减速)出现,在用户退出脚本之前永远不会消失.如果是真的,那么这很可能是不好的做法而且是不可取的,这意味着必须有另一种选择?
每当你有Python代码时:
回想相同的功能,这样如果用户没有选择其他一个语句然后他们可以再次尝试而不是程序停止工作,
你几乎总是更好地用循环替换递归调用.在这种情况下,递归是完全没有必要的,可能浪费资源,并可能使代码更难遵循.
编辑:现在您已经发布了代码,我建议将其重新命名为状态机.以下页面提供了可能有用的Python模块的摘要:link.
即使没有任何额外的模块,您的代码也适用于简单的非递归重写:
import sys
def function_four():
# Does Stuff
return function_one
def function_three():
# Does Stuff
return function_two
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
return function_three
elif usr_input == '2':
return None
else:
print("Did not recognise command. Try again.")
return function_one
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
return function_four
elif usr_input == '2':
return function_three
elif usr_input == '3':
return None
else:
print("Did not recognise command. Try again.")
return function_two
state = function_one
while state is not None:
state = state()
Run Code Online (Sandbox Code Playgroud)
请注意,这些功能不再相互调用.相反,它们中的每一个都返回下一个要调用的函数,顶层循环负责调用.
| 归档时间: |
|
| 查看次数: |
701 次 |
| 最近记录: |