如何退出Python中的一些中间函数
调用堆栈为:如何退出Python中的一些中间函数,python,python-3.x,Python,Python 3.x,调用堆栈为:explore()->无法修改()-->check() 如果我在check中满足某些条件,我想退出check并且无法修改并返回浏览。 那么我如何才能做到这一点呢 我曾考虑在check函数中引发一种特定类型的异常,并在explore中捕获它,但该异常可以在函数中捕获,不能修改 有人有想法吗 谢谢即使这不是最优雅的解决方案,您也可以决定在check函数中引发异常(或),并在explorer函数中捕获该异常。确保您只捕获了您的异常 def check(): if (cond):
explore()->无法修改()-->check()
如果我在check
中满足某些条件,我想退出check
并且无法修改
并返回浏览
。
那么我如何才能做到这一点呢
我曾考虑在check
函数中引发一种特定类型的异常,并在explore
中捕获它,但该异常可以在函数中捕获,不能修改
有人有想法吗
谢谢即使这不是最优雅的解决方案,您也可以决定在check
函数中引发异常(或),并在explorer
函数中捕获该异常。确保您只捕获了您的异常
def check():
if (cond):
how to return back to explore()
else:
return 1 # here return to f2
def cannot_be_modified():
try:
check() # inserted
print("hello from cannot_be_modified")
return 2
except Exception as e:
print(e)
def explore():
cannot_be_modified()
print("hello from explore")
return 0
explore()
输出:
def check():
if True:
raise ValueError("MyError")
else:
return 1 # here return to f2
def cannot_be_modified():
check() # inserted
print("hello from cannot_be_modified")
return 2
def explore():
try:
cannot_be_modified()
except ValueError as e:
print(e)
print("hello from explore")
return 0
explore()
如果每个函数中都有一些条件,您是否可以提前返回?此线程可能会帮助您:您的意思是您不能修改cannot_\u modified
中的代码?您是否想过使用异常来执行此操作?请先阅读此文,以了解此方法中的缺陷,但我认为它会起作用。@t点击:我们只能在不能修改
函数中添加检查
,不能修改任何其他内容。@Paula Thomas:我可以在check
中引发异常,但它可以被不能修改捕获和处理,也不能到达explore
Hi@Gsk:不能修改这里没有try
但是不能修改是由另一方实现的,它可能有try
,并且可以从check()
捕获异常。然后explore()
无法捕获该异常。我为这种情况修改了无法修改。看看异常是如何工作的,然后试试我的代码!您不必使用无法修改
执行任何操作:如果此第三方函数中的异常处理正确(即没有try/except
捕获所有内容),则异常将引发,直到您的explore
函数如果无法修改
函数中没有try/except
,您的解决方案是正确的,但是如果无法修改
具有尝试/排除
,则探索
无法从检查
捕获异常。因为不能被修改
不能被第三方修改和实现,所以他们可以任意编写他们想要的任何东西。
MyError
hello from explore