`>>> 和有什么不一样?some_object` 和 `>>>在 Python 解释器中打印 some_object`? [英] What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter?
问题描述
在解释器中你可以只写一个对象的名字,例如一个列表 a = [1, 2, 3, u"hello"]
在解释器提示符下,如下所示:
或者你可以这样做:
<预><代码>>>>打印一个[1, 2, 3, 你见鬼xf6']这对于列表来说似乎是等价的.目前我正在使用 hdf5 来管理一些数据,我意识到上面提到的两种方法之间存在差异.鉴于:
with tables.openFile("tutorial.h5", mode = "w", title = "Some Title") 作为 h5file:group = h5file.createGroup("/", '节点', '节点信息')table.table = h5file.createTable(group, 'readout', Node, "Readout example")
输出
打印 h5file
不同于
<预><代码>>>>h5文件所以我想知道是否有人可以解释 Python 在这两种情况下的行为差异?
在终端中键入一个对象会调用 __repr__()
,它用于详细表示您正在打印的对象(无歧义).当你告诉打印"某些东西时,你正在调用 __str__()
并因此要求一些人类可读的东西.
Alex Martelli 这里.线程中的其他回复也可能说明差异.
例如,看看日期时间对象.
<预><代码>>>>导入日期时间>>>现在 = datetime.datetime.now()比较...
<预><代码>>>>现在出: datetime.datetime(2011, 8, 18, 15, 10, 29, 827606)到...
<预><代码>>>>现在打印出:2011-08-18 15:10:29.827606希望能让它更清楚一点!
In the interpreter you can just write the name of an object e.g. a list a = [1, 2, 3, u"hellö"]
at the interpreter prompt like this:
>>> a
[1, 2, 3, u'hellxf6']
or you can do:
>>> print a
[1, 2, 3, u'hellxf6']
which seems equivalent for lists. At the moment I am working with hdf5 to manage some data and I realized that there is a difference between the two methods mentioned above. Given:
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")
The output of
print h5file
differs from
>>> h5file
So I was wondering if someone could explain Python's behavioral differences in these two cases?
Typing an object into the terminal calls __repr__()
, which is for a detailed representation of the object you are printing (unambiguous). When you tell something to 'print', you are calling __str__()
and therefore asking for something human readable.
Alex Martelli gave a great explanation here. Other responses in the thread might also illuminate the difference.
For example, take a look at datetime objects.
>>> import datetime
>>> now = datetime.datetime.now()
Compare...
>>> now
Out: datetime.datetime(2011, 8, 18, 15, 10, 29, 827606)
to...
>>> print now
Out: 2011-08-18 15:10:29.827606
Hopefully that makes it a little more clear!
这篇关于`>>> 和有什么不一样?some_object` 和 `>>>在 Python 解释器中打印 some_object`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!