为什么在python中的“ try:”块中的return语句之后执行“ finally:”块?

时间:2018-11-04 11:55:26

标签: python python-2.7 return

根据我的理解:返回是返回值的意思。

一个示例,python1脚本:

def func():  
    try:  
       print 98  
       return 'ok' 
    finally: 
       print 98  

print fun()  

脚本的输出为:

98

98

所以我的问题是为什么脚本的输出不是:

98

98

为什么OK行的末尾输出?

1 个答案:

答案 0 :(得分:-1)

因为使用

try:
  #some code
finally:
  #some other code

无论finally块中发生了什么,都保证try块在try块之后执行。即使没有提出异常。

finally通常用于释放资源,清除变量等。

相关问题