从子函数中的父函数返回

DYD*_*DYD 3 python return function python-3.x

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

def function():
    return
Run Code Online (Sandbox Code Playgroud)

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

例子:

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

Run Code Online (Sandbox Code Playgroud)

我尝试提出一个Exception,正如这个答案所暗示的那样,但这只是退出了整个程序。

dsp*_*cer 5

您可以从 引发异常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")
Run Code Online (Sandbox Code Playgroud)

输出:

This is the parent function
This is the child function
This should still be able to print
Run Code Online (Sandbox Code Playgroud)