重温python3中的函数

2024-04-19 18:00:14 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的脚本中,我有以下四个函数:

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()

我需要知道这是否会导致我认为会出现的问题:函数永远不会关闭,导致大量打开的函数(可能还会浪费内存并最终减慢速度)出现,直到用户退出脚本才会消失。如果是真的,那么这很可能是不好的做法和不可取的,这意味着必须有一个替代方案?在


Tags: 函数脚本inputusrdeffunctiononequit
1条回答
网友
1楼 · 发布于 2024-04-19 18:00:14

每当您有Python代码时:

Recalling The Same Function So That If The User Does Not Chose One Of The Other Statements Then They Can Try Again Rather Than The Program To Stop Working,

用循环替换递归调用几乎总是更好。在这种情况下,递归是完全不必要的,可能会浪费资源,并且可能会使代码更难理解。在

编辑:既然您已经发布了代码,我建议将其重新设计为state machine。下一页提供了可能有用的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()

请注意,这些函数不再互相调用。相反,它们都返回下一个要调用的函数,顶级循环负责调用。在

相关问题 更多 >