[英]Why "finally:" block is executed after the return statement in a "try:" block in python?
According to my understanding:return is the meaning of returning a value.按照我的理解:return就是返回一个值的意思。
One example, the python1 script:一个例子,python1 脚本:
def func():
try:
print 98
return 'ok'
finally:
print 98
print fun()
The output of the script is :脚本的输出是:
98 98
98 98
ok好的
So my question is why the output of the script is not:所以我的问题是为什么脚本的输出不是:
98 98
OK好的
98 98
Why is the output of the OK line at the end?为什么最后是OK行的输出?
Because when you use因为当你使用
try:
#some code
finally:
#some other code
the finally
block is guaranteed to be executed after the try
block no matter what happens in the try
block.无论在try
块中发生什么, finally
块都保证在try
块之后执行。 Even if no exception was raised.即使没有引发异常。
finally
is generally used to release resources, clean up of variables etc. finally
一般用于释放资源、清理变量等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.