Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

printing - What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...