python - 为什么 Python 数据类型在 Python 提示符中表现得像这样?

标签 python python-3.x terminal read-eval-print-loop

在终端中摆弄 python 时,我注意到了一些奇怪的事情。如果您输入诸如 1+2*3 之类的表达式,终端将输出 7,这很奇怪,因为它不应该打印任何东西,但它确实打印了。但是,如果您使用诸如 print("hello world") 之类的函数,它将输出 hello world,而不是 print 返回的 None。此外,输入 True 输出 True,输入 False 输出 False,但输入 None不输出任何东西。 python 如何决定何时输出一个值?

最佳答案

当您计算一个表达式时究竟发生了什么由 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 - 为什么 Python 数据类型在 Python 提示符中表现得像这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44739517/

相关文章:

python - 如何在屏幕上显示和更新分数?

python - 检查树是否为二叉搜索树 (BST)

linux - Bash 命令记录器

python - 如何按特定顺序从列表中获取唯一值?

python - Cython 是用于构建 C 代码还是用于构建 Python 扩展?

python-3.x - 使用 pytest,如何将 pathlib 的 Path.isdir() 函数与 os.listdir 一起模拟

xcode - xcode-select --install失败

bash - Broken Homebrew - 输入 "brew"+ 任何内容时出现回溯错误

python - Pandas:选择两行之间的所有行

python 3 : How to print a program that validates strings