gpt4 book ai didi

python - 如何退出Python中的一些中间函数

转载 作者:行者123 更新时间:2023-12-01 09:25:19 24 4
gpt4 key购买 nike

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

调用堆栈为:explore() ->cannot_be_modified()-->check()

如果我在check中满足某些条件,我想退出checkcannot_be_modified并返回explore。那么我怎样才能实现这一目标呢?

我考虑过在 check 函数中引发特定类型的异常,并在 explore 中捕获它,但该异常可以在函数 cannot_be_modified 中捕获

有人有想法吗?

谢谢

最佳答案

即使这不是最优雅的解决方案,您也可以决定在 check 中引发异常( built-incustom )函数并在 explorer 中捕获它功能。确保您只捕获异常。

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

输出:

MyError
hello from explore

关于python - 如何退出Python中的一些中间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50463095/

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