Python 从子函数中的父函数返回
我知道在函数中,您可以使用Python 从子函数中的父函数返回,python,python-3.x,function,return,Python,Python 3.x,Function,Return,我知道在函数中,您可以使用return退出函数 def函数(): 返回 但是您可以从子函数退出父函数吗 例如: def函数() 打印(“这是父函数”) def exit_two(): 打印(“这是子函数”) #以某种方式退出此函数(同时退出)并退出父函数(函数) 退出 打印(“这不应该打印”) 函数() 打印(“应该仍然可以打印”) 正如建议的那样,我尝试引发一个异常,但这只会退出整个程序。您可以从exit\u两者引发一个异常,然后在调用函数的地方捕捉该异常,以防止程序退出。我在这里使用自
return
退出函数
def函数():
返回
但是您可以从子函数退出父函数吗
例如:
def函数()
打印(“这是父函数”)
def exit_two():
打印(“这是子函数”)
#以某种方式退出此函数(同时退出)并退出父函数(函数)
退出
打印(“这不应该打印”)
函数()
打印(“应该仍然可以打印”)
正如建议的那样,我尝试引发一个
异常
,但这只会退出整个程序。您可以从exit\u两者
引发一个异常,然后在调用函数
的地方捕捉该异常,以防止程序退出。我在这里使用自定义异常,因为我不知道有合适的内置异常,因此要避免捕获异常
本身
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
一种解决办法是:
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")
请注意,您选择在
函数
中同时定义退出
这一事实是完全不相关的,与使用两个“正常定义”的函数相比,这种情况更不清楚。这个问题是否与tkinter
有关?一个函数不应该知道是谁首先调用了它;函数的任务不是指定调用应返回的位置。例外情况是发出问题发生的信号,而不是直接进行流控制(Python使用了StopIteration
等)。jizhihaoSAMA是的,确实如此。您必须只返回吗?还是返回值?我想返回值可以通过设置exception.value来适应,但这是需要记住的。