gpt4 book ai didi

python - 带有 Return 语句的奇怪的 Try-Except-Else-Finally 行为

转载 作者:行者123 更新时间:2023-11-28 19:19:18 27 4
gpt4 key购买 nike

这是一些行为异常的代码。这是我编写的行为的简化版本。这仍然会展示奇怪的行为,我对为什么会发生这种情况有一些具体问题。

我在 Windows 7 上使用 Python 2.6.6。

def demo1():
try:
raise RuntimeError,"To Force Issue"
except:
return 1
else:
return 2
finally:
return 3

def demo2():
try:
try:
raise RuntimeError,"To Force Issue"
except:
return 1
else:
return 2
finally:
return 3
except:
print 4
else:
print 5
finally:
print 6

结果:

>>> print demo1()
3
>>> print demo2()
6
3
  • 为什么演示 1 返回 3 而不是 1?
  • 为什么演示二打印 6 而不是打印 6 w/4 或 5?

最佳答案

因为 finally 语句是保证被执行的(好吧,假设没有断电或任何超出 Python 控制的事情)。这意味着在函数返回之前,它必须运行 finally block ,该 block 返回不同的值。

Python docs状态:

When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

这意味着当您尝试返回时,将调用 finally block ,返回它的值,而不是您本来拥有的值。

关于python - 带有 Return 语句的奇怪的 Try-Except-Else-Finally 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29101196/

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