为什么在交互式Python中返回会打印到系统标准?

2024-09-27 14:16:02 发布

您现在位置:Python中文网/ 问答频道 /正文

今天我遇到了不一样的事。考虑这个简单的函数:

def hi():
    return 'hi'

如果我在Python shell中调用它

^{pr2}$

它输出“returned”值,即使它只是repr。这让我觉得很奇怪,怎么会回到stdout打印呢?因此我将其更改为要运行的脚本:

def hi():
    return 'hi'
hi()

我从终端查到的:

Last login: Mon Jun  1 23:21:25 on ttys000
imac:~ zinedine$ cd documents
imac:documents zinedine$ python hello.py
imac:documents zinedine$ 

似乎没有产出。然后,我开始觉得这是一件无聊的事,所以我试了一下:

Last login: Tue Jun  2 13:07:19 on ttys000
imac:~ zinedine$ cd documents
imac:documents zinedine$ idle -r hello.py

以下是Idle中显示的内容:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> 
>>> 

因此,在交互式pythonshell中只返回prints。这是特写吗?这应该发生吗?这有什么好处?在


Tags: 函数pyhelloreturnondefcdlogin
3条回答

首先,它不是return宁,也与函数无关。你只有一个表达式,它的计算结果是一个对象(大惊喜!Python中的一切都是一个对象)。在

在这种情况下,解释器可以选择要显示的内容。您使用的解释器显然使用__repr__。如果你使用IPython,你会看到一个whole protocol,这取决于前端,决定将显示什么。在

在Python的交互模式中,计算为某个值的表达式将打印其repr()(表示形式)。这样您就可以:

4 + 4

而不是必须:

^{pr2}$

例外情况是表达式的计算结果为None。这不是印刷品。在

您的函数调用是一个表达式,它的计算结果是函数的返回值,它不是None,因此它被打印出来。在

有趣的是,这不仅仅适用于最后评估的值!任何由计算为某个(非None)值的表达式组成的语句都将打印该值。即使在循环中:

for x in range(5): x

不同的Python命令行可以用不同的方式处理这个问题;这是标准pythonshell所做的。在

交互式解释器将打印您键入并执行的表达式返回的任何内容,以方便测试和调试。在

>>> 5
5
>>> 42
42
>>> 'hello'
'hello'
>>> (lambda : 'hello')()
'hello'
>>> def f():
...     print 'this is printed'
...     return 'this is returned, and printed by the interpreter'
...
>>> f()
this is printed
'this is returned, and printed by the interpreter'
>>> None
>>>

请参阅Wikipedia上的Read–eval–print loop以了解更多信息。在

相关问题 更多 >

    热门问题