gpt4 book ai didi

python - 从子函数中的父函数返回

转载 作者:行者123 更新时间:2023-12-04 02:37:30 24 4
gpt4 key购买 nike

我知道在函数中你可以使用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")


我尝试引发一个Exception,如this answer建议,但这只会退出整个程序。

最佳答案

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

关于python - 从子函数中的父函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60975800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com