当我在 Python 或 IPython 控制台中时,返回输出时调用什么?

When I am in the Python or IPython console, what is called when I am returned an output?

例如,

python
>> x = 1
>> x
1

我很好奇 x 上的 method/function 返回了什么 1。我之所以问是因为我发现调用 print x 和调用 x 之间存在差异.

同理,有没有办法指定叫什么? IPython中是否存在此配置?

当您在 REPL, it invokes the object's __repr__ method. In comparison, print uses the object's __str__ 方法中以这种方式检查对象时。示例:

>>> class Widget:
...     def __repr__(self):
...             return "repr of a Widget"
...     def __str__(self):
...             return "str of a Widget"
...
>>> x = Widget()
>>> x
repr of a Widget
>>> print(x)
str of a Widget
>>> print([x,2,3])
[repr of a Widget, 2, 3]
>>> print(repr(x))
repr of a Widget
>>> print(str(x))
str of a Widget

在为您自己的 类 定义 __repr____str__ 时,请尝试遵循文档关于哪一个应该更详细的建议以及 "official".

[__repr__ computes] the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
...
[__str__ computes] the “informal” string representation of an object. The return value must be a string object. This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

另一个答案在香草 Python REPL 中解决了 repr,但它忽略了关于 IPython 的回答,works quite differently 并且具有更多功能(和复杂性) ) 关于 REPL 打印。

这是一个差异示例:

# vanilla python:
>>> type([])
<class 'list'>

# in IPython:
>>> type([])
list

IPython 有一个 custom pretty printer 和 public 钩子用于在 ​​IPython 中自定义 repr。一个这样的钩子是 _repr_pretty_(单下划线!)这是一个基本的例子:

>>> class Widget:
...     def __repr__(self):
...         "vanilla"
...     def _repr_pretty_(self, p, cycle):
...         p.text("chocolate, strawberry")
...         
>>> Widget()
chocolate, strawberry

有关更多功能,请参阅文档中的“Integrating your objects with IPython”,尤其是 Rich display 部分。