【发布时间】: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