从子函数的父函数返回

时间:2020-04-01 16:32:15

标签: python python-3.x function return

我知道您可以在函数中使用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,但这只是退出了整个程序。

2 个答案:

答案 0 :(得分:4)

您可以从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

答案 1 :(得分:0)

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

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