【问题标题】:Revisiting Functions In Python 3重温 Python 3 中的函数
【发布时间】:2012-03-11 04:28:16
【问题描述】:

在我的脚本中,我有四个这样工作的函数:

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

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

【问题讨论】:

  • 我们可以看到代码而不是对其进行口头描述吗?另外,功能三和四的意义何在?
  • @tzaman Here is the simplified code。除了简单地调用其他函数之外,还有一些事情发生,但它们对这个问题并不重要,所以为了简单起见,我把它们省略了。
  • 这段代码刚刚让我的 Python 3.2 崩溃了——我不是指 RuntimeException,我指的是真正的崩溃——出现“致命的 Python 错误:无法从堆栈溢出中恢复。中止陷阱”消息.诚然,我不得不按住返回键一分钟,但还是这样。
  • @Eden:你可以edit你的问题,直接用你的代码替换你的varbal描述。真正的代码比它的描述更容易理解。
  • 我为您编辑了问题 Rik Poggi。 Tzaman:最后一行在我的链接中没有正确对齐,它应该在最左边,详情请参阅问题。帝斯曼:奇怪。为我工作。 “sys.exit()”需要“include sys”,但除此之外我不知道问题可能是什么。

标签: python function memory python-3.x


【解决方案1】:

只要你有 Python 代码:

调用相同的函数,这样如果用户没有选择其他语句之一,那么他们可以重试而不是程序停止工作,

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

编辑:既然您已经发布了代码,我建议您将其重铸为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()

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

【讨论】:

  • 另外,每当你有这样的事情时,你最好看看英文大写和小写是如何工作的。此外,当您有一种支持尾调用优化的语言时,这并不成立
  • @NiklasB.:关于学习正确大写的内容,English这个词用大写E拼写。至于尾递归,这个问题专门针对 Python。
  • "Touché" 如果不是因为最小评论大小,我会回答这个问题。一定错过了[python]标签,因为问题o.O中没有Python代码
  • 感谢 aix 的建议,即使它没有回答我的问题。
  • @EdenCrow:不确定您是否看过我的编辑,但我建议您将代码重写为简单的状态机。