带有 Return 语句的奇怪 Try-Except-Else-Finally 行为 [英] Weird Try-Except-Else-Finally behavior with Return statements

查看:51
本文介绍了带有 Return 语句的奇怪 Try-Except-Else-Finally 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在 Windows 7 上使用 Python 2.6.6.

def demo1():尝试:引发运行时错误,强制问题"除了:返回 1别的:返回 2最后:返回 3定义演示2():尝试:尝试:引发运行时错误,强制问题"除了:返回 1别的:返回 2最后:返回 3除了:打印 4别的:打印 5最后:打印 6

结果:

<预><代码>>>>打印演示1()3>>>打印演示2()63

  • 为什么演示版返回 3 而不是 1?
  • 为什么演示二打印 6 而不是打印 6 w/4 或 5?

解决方案

因为 finally 语句保证被执行(好吧,假设没有停电或任何超出Python 的控制).这意味着在函数可以返回之前,它必须运行 finally 块,它返回一个不同的值.

Python 文档 状态:

<块引用>

当在 try...finally 语句的 try 套件中执行 return、break 或 continue 语句时,finally 子句也会在出路时"执行.

函数的返回值由最后执行的返回语句决定.由于finally子句总是执行,finally子句中执行的return语句将永远是最后执行的:

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

This is some code that is behaving peculiarly. This is a simplified version of the behavior that I've written. This will still demonstrate the weird behavior and I had some specific questions on why this is occurring.

I'm using Python 2.6.6 on Windows 7.

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

Results:

>>> print demo1()
3
>>> print demo2()
6
3

  • Why is demo one returning 3 instead of 1?
  • Why is demo two printing 6 instead of printing 6 w/ 4 or 5?

解决方案

Because finally statements are guaranteed to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.

The Python docs state:

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:

This means that when you try to return, the finally block is called, returning it's value, rather than the one that you would have had.

这篇关于带有 Return 语句的奇怪 Try-Except-Else-Finally 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆