printing - Python 解释器中的 `>>> some_object` 和 `>>> print some_object` 有什么区别?

标签 printing behavior python

在解释器中你可以只写一个对象的名字,例如一个列表 a = [1, 2, 3, u"hellö"] 在解释器提示符下像这样:

>>> a
[1, 2, 3, u'hell\xf6']

或者你可以这样做:

>>> print a
[1, 2, 3, u'hell\xf6']

这对于列表来说似乎是等价的。目前我正在使用 hdf5 管理一些数据,我意识到上述两种方法之间存在差异。鉴于:

with tables.openFile("tutorial.h5", mode = "w", title = "Some Title") as h5file:
    group = h5file.createGroup("/", 'node', 'Node information')
    tables.table = h5file.createTable(group, 'readout', Node, "Readout example")

输出

print h5file

不同于

>>> h5file

所以我想知道是否有人可以解释 Python 在这两种情况下的行为差异?

最佳答案

在终端中键入一个对象会调用 __repr__(),它用于详细表示您正在打印的对象(明确)。当您告诉要“打印”的内容时,您正在调用 __str__(),因此要求提供一些人类可读的内容。

Alex Martelli 给出了很好的解释 here .线程中的其他响应也可能会说明差异。

例如,查看日期时间对象。

>>> import datetime
>>> now = datetime.datetime.now()

比较...

>>> now
Out: datetime.datetime(2011, 8, 18, 15, 10, 29, 827606)

为了...

>>> print now
Out: 2011-08-18 15:10:29.827606

希望这能让它更清楚一点!

关于printing - Python 解释器中的 `>>> some_object` 和 `>>> print some_object` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7114675/

相关文章:

ruby-on-rails-3 - 有谁知道印有T恤和杯子的Rails 3 gem 吗?

php - 将鼠标悬停在图像上,获取打印对话框?

python - 当将 text() 与 python-escpos 一起使用时,我得到 [Errno None] 和关键错误 = 1 (windows 10)

python - 使用哪个 : OneToOne vs ForeignKey?

python - 使用python替换图像中的白色行

css - Chrome 打印网站,缺少布局选项

c# - System.Web.Configuration.WebConfigurationManager 和 System.Configuration.ConfigurationManager 之间的行为差​​异

erlang - 是否有一种 Erlang 行为可以自行行动而不是等待被调用?

python - 解决 Hettinger 示例的异步三重奏方法