在解释器中你可以只写一个对象的名字,例如一个列表 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/