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

Hex*_*nic 2 python

很高兴能够在shell中输入一个对象并获得一些东西,例如,

>>>foo
I am foo
Run Code Online (Sandbox Code Playgroud)

通常,print(foo)在模块脚本中使用将产生相同的结果,如上面的情况(我使用的是Python 3.5).但通常情况下,对于复杂类的实例,您可以得到截然不同的输出.

这提出了一个问题,当您键入对象名称并在交互式python shell中按Enter键时会发生什么?什么内置被称为?

例:

在模块中:

print(h5file)
Run Code Online (Sandbox Code Playgroud)

输出:

tutorial1.h5(文件)'测试文件'最后修改:'Wed Jun 8 21:18:10 2016'对象树:/(RootGroup)'测试文件'/探测器(组)'探测器信息'/探测器/读出器(表(0,))'读出示例'

与shell输出对比

>>> h5file文件(filename = tutorial1.h5,title ='Test file',mode ='w',root_uep ='/',filters = Filters(complevel = 0,shuffle = False,fletcher32 = False,least_significant_digit = None ))/(RootGroup)'测试文件'/检测器(组)'检测器信息'/检测器/读数(表(0,))'读出示例'描述:= {"国家":UInt16Col(形状=(),dflt = 0,pos = 0),"Geo":UInt16Col(shape =(),dflt = 0,pos = 1),"HsCode":Int8Col(shape =(),dflt = 0,pos = 2),"月" ":UInt16Col(shape =(),dflt = 0,pos = 3),"Quantity":UInt16Col(shape =(),dflt = 0,pos = 4),

Tim*_*ers 5

print隐式应用于str()每个打印项以获取字符串,而shell隐式应用于repr()获取字符串.所以它是对象__str__()__repr__()方法之间的差异(如果有的话)

>>> 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!
Run Code Online (Sandbox Code Playgroud)

请注意,我忽略了您使用的shell覆盖默认sys.displayhook函数的可能性.