在交互式Python shell中输入对象时调用什么内置函数?

在交互式Python shell中输入对象时调用什么内置函数?,python,Python,能够在壳中输入一个对象,然后取回一些东西,这很好,例如 >>>foo I am foo 通常,在模块脚本中使用print(foo)将产生与上述情况相同的结果(我使用的是Python 3.5)。但通常,对于复杂类的实例,您可以获得完全不同的输出 这就提出了一个问题,当您在交互式python shell中键入对象名并按enter键时,会发生什么情况?什么是内置的 示例: 模块中: print(h5file) 输出: tutorial1.h5(文件)‘测试文件’最后一次修改:“W

能够在壳中输入一个对象,然后取回一些东西,这很好,例如

>>>foo
I am foo
通常,在模块脚本中使用
print(foo)
将产生与上述情况相同的结果(我使用的是Python 3.5)。但通常,对于复杂类的实例,您可以获得完全不同的输出

这就提出了一个问题,当您在交互式python shell中键入对象名并按enter键时,会发生什么情况?什么是内置的

示例:

模块中:

print(h5file)
输出:

tutorial1.h5(文件)‘测试文件’最后一次修改:“Wed Jun 8 21:18:10 2016’对象树:/(根组)‘测试文件’/检测器(组)‘检测器信息’/检测器/读数(表(0),)‘读数示例’

与外壳输出的对比

>>>h5file File(filename=tutorial1.h5,title='Test File',mode='w',root'u uep='/',filters=filters(complevel=0,shuffle=False,fletcher32=False,least'u-signific_-digit=None))/(RootGroup)'Test File'/detector(Group)'detector-information'/detector/readout(表(0,)'reading-example'说明:={“Country”:UInt16Col(形状=(),dflt=0,pos=0),“Geo”:UInt16Col(shape=(),dflt=0,pos=1),“HsCode”:Int8Col(shape=(),dflt=0,pos=2),“Month”:UInt16Col(shape=(),dflt=0,pos=3),“Quantity”:UInt16Col(shape=(),dflt=0,pos=4)


在REPL中,
\uuuuu repr\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

pax> python
Python 2.7.9 (default, Jun  1 2016, 16:07:34) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class xyzzy:
...     def __repr__(self):
...         return "me"
...     def __str__(self):
...         return "other-me"
... 
>>> plugh = xyzzy()
>>> plugh
me
>>> print plugh
other-me
\uuuu repr\uuuu()
是在这种情况下调用的方法。它返回对象的“正式”(规范)表示形式,而
\uuuuu str\uuuuu
的结构通常较低


比较
repr
vs
str

>>> class A: pass
... 
>>> A
<class __main__.A at 0x101c609a8>
>>> A()
<__main__.A instance at 0x101cea488>
>>> print A
__main__.A
>>> repr(A)
'<class __main__.A at 0x101c609a8>'
>>> str(A)
'__main__.A'

print
隐式地将
str()
应用于每个打印项以获取字符串,而shell隐式地将
repr()
应用于获取字符串。因此,这就是对象的
\uu str\uuuuuuuuuuuuuuuuu()和
\uuuuuu repr\uuuuuuuuuuuuuuu()方法之间的差异(如果有的话)

>>> class A(object):
...    def __str__(self):
...        return "I'm friendly!"
...    def __repr__(self):
...        return "If different, I'm generally more verbose!"

>>> a = A()
>>> print(a)
I'm friendly!
>>> a
If different, I'm generally more verbose!

请注意,我忽略了这样一种可能性,即您使用的shell已经覆盖了默认的
sys.displayhook
函数。

它是对象的
repr
vs
str
,因此要获得与模块中REPL相同的结果,可以使用print(repr(h5file))。这很有效。谢谢。@Hexatonic,是的,
repr()
call为您提供了一个字符串,该字符串与您只需将对象输入REPL即可得到的字符串相匹配。当然,
print()
对该字符串调用
str()
,基本上是一个不可操作的字符串,为您提供了表示形式。@Hexatonic:FWIW,在使用
{!r}的format函数或方法时,您可以轻松获得对象的repr
而不是格式字符串中的
{}
。@Hexatonic:Tim Peters对Python内部的了解非常多。:)
>>> class A(object):
...    def __str__(self):
...        return "I'm friendly!"
...    def __repr__(self):
...        return "If different, I'm generally more verbose!"

>>> a = A()
>>> print(a)
I'm friendly!
>>> a
If different, I'm generally more verbose!