【问题标题】:Return from parent function in a child function在子函数中从父函数返回
【发布时间】:2020-07-13 11:49:48
【问题描述】:

我知道在函数中你可以使用return 退出函数,

def function():
    return

但是你可以从子函数中退出父函数吗?

例子:

def function()
    print("This is the parent function")

    def exit_both():
        print("This is the child function")
        # Somehow exit this function (exit_both) and exit the parent function (function)

    exit_both()
    print("This shouldn't print")

function()
print("This should still be able to print")


按照this answer 的建议,我尝试提出Exception,但这只会退出整个程序。

【问题讨论】:

  • 请注意,您选择在 function 内定义 exit_both 的事实完全无关紧要,只是使情况比使用两个“通常定义的”函数更不清晰。
  • 这个问题和tkinter有关系吗?
  • 一个函数首先不应该知道是谁调用了它;指定调用应返回的位置不是函数的工作。异常是用于发出问题的信号,而不是直接用于流控制(Python 使用 StopIteration 等除外。)
  • @jizhihaoSAMA 是的。
  • 你只需要return吗?或返回值?我想可以通过设置一个 exception.value 来适应返回值,但要记住这一点。

标签: python python-3.x function return


【解决方案1】:

您可以从exit_both 引发异常,然后在调用function 的地方捕获异常,以防止程序退出。我在这里使用自定义异常,因为我不知道合适的内置异常,并且要避免捕获 Exception 本身。

class MyException(Exception):
    pass

def function():
    print("This is the parent function")

    def exit_both():
        print("This is the child function")
        raise MyException()

    exit_both()
    print("This shouldn't print")

try:
    function()
except MyException:
    # Exited from child function
    pass
print("This should still be able to print")

输出:

This is the parent function
This is the child function
This should still be able to print

【讨论】:

    【解决方案2】:

    一个解决方案可能是这样的:

    returnflag = False
    def function():
        global returnflag
        print("This is the parent function")
    
        def exit_both():
            global returnflag
            print("This is the child function")
            returnflag = True
            return
    
        exit_both()
        if returnflag == True:
            return
        print("This shouldn't print")
    
    function()
    print("This should still be able to print")
    

    或者如果你不喜欢玩全局变量,你可以试试这个:

    def function():
        returnflag = False
        # or you can use function.returnflag = False -> the result is the same
        print("This is the parent function")
    
        def exit_both():
            print("This is the child function")
            function.returnflag = True
            return
    
        exit_both()
        if function.returnflag == True:
            return
        print("This shouldn't print")
    
    function()
    print("This should still be able to print")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2015-02-13
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多