为什么 Python 数据类型在 Python 提示符中表现得像这样?
Why Python datatypes behave like this in Python prompt?
在终端中摆弄 python 时,我注意到了一些奇怪的事情。如果你输入一个表达式,如 1+2*3
,终端将输出 7,这很奇怪,因为它不应该打印任何东西,但它确实打印了。但是如果你使用像 print("hello world") 这样的函数,它会输出 hello world
,而不是 None
,也就是 printreturns。此外,输入 True
输出 True
,输入 False
输出 False
,但输入 None
不会输出任何内容。 python如何决定何时输出一个值?
终端中的 python 会话被称为 REPL,或 Read-Evaluate-Print-Loop,它接受输入,对其进行评估并 returns 结果。查看 wikipedia page。
您看到的是 Python REPL(读取-评估-打印-循环)。
大多数 REPL(包括 Python 的 REPL)将使用 在线解析器:一个构建表达式树的解析器。从构建表达式树的那一刻起,REPL 将评估它(这可以是一个函数定义,在这种情况下函数被解析和分析)。求值后,REPL会得到结果,检查结果*。如果是None
,则不打印结果。顺便说一句,作业也是如此。
例如:
>>> None # None is not printed
>>> a = 2 # assignments are not printed
>>>
如果结果是不是 None
,那么它将调用repr(..)
内置方法,从而打印文本结果的表示。
计算表达式时具体发生的情况由 sys.displayhook
决定。来自 docs:
sys.displayhook(value)
If value
is not None
, this function prints it to sys.stdout
, and saves it in __builtin__._
.
sys.displayhook
is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook
.
取消 None
特殊情况的简单覆盖示例:
>>> def new_hook(x):
... print(repr(x))
...
>>> sys.displayhook = new_hook
>>> 3
3
>>> None
None
在终端中摆弄 python 时,我注意到了一些奇怪的事情。如果你输入一个表达式,如 1+2*3
,终端将输出 7,这很奇怪,因为它不应该打印任何东西,但它确实打印了。但是如果你使用像 print("hello world") 这样的函数,它会输出 hello world
,而不是 None
,也就是 printreturns。此外,输入 True
输出 True
,输入 False
输出 False
,但输入 None
不会输出任何内容。 python如何决定何时输出一个值?
终端中的 python 会话被称为 REPL,或 Read-Evaluate-Print-Loop,它接受输入,对其进行评估并 returns 结果。查看 wikipedia page。
您看到的是 Python REPL(读取-评估-打印-循环)。
大多数 REPL(包括 Python 的 REPL)将使用 在线解析器:一个构建表达式树的解析器。从构建表达式树的那一刻起,REPL 将评估它(这可以是一个函数定义,在这种情况下函数被解析和分析)。求值后,REPL会得到结果,检查结果*。如果是None
,则不打印结果。顺便说一句,作业也是如此。
例如:
>>> None # None is not printed
>>> a = 2 # assignments are not printed
>>>
如果结果是不是 None
,那么它将调用repr(..)
内置方法,从而打印文本结果的表示。
计算表达式时具体发生的情况由 sys.displayhook
决定。来自 docs:
sys.displayhook(value)
If
value
is notNone
, this function prints it tosys.stdout
, and saves it in__builtin__._
.
sys.displayhook
is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function tosys.displayhook
.
取消 None
特殊情况的简单覆盖示例:
>>> def new_hook(x):
... print(repr(x))
...
>>> sys.displayhook = new_hook
>>> 3
3
>>> None
None