问题描述
例如,
python
>> x = 1
>> x
1
我很想知道 x 正在返回1.我问,因为我看到调用 print x
和简单地 x 。
I'm curious about what method/function on x
is returning 1. I'm asking because I'm seeing differences between calling print x
and simply x
.
同样,有没有办法指定所谓的内容? IPython中是否存在此配置?
Similary, is there a way to specify what is called? Does this configuration exist in IPython?
推荐答案
当您在,它调用对象的方法。相比之下, print
使用对象的方法。示例:
When you inspect an object in that manner in a REPL, it invokes the object's __repr__
method. In comparison, print
uses the object's __str__
method. Example:
>>> 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
定义<$ c $时c> __ repr __ 和 __ str __
对于您自己的课程,请尝试遵循文档中有关哪一个应该更详细和官方的建议。
When defining __repr__
and __str__
for your own classes, try to follow the documentation's suggestions regarding which one should be more detailed and "official".
这篇关于当我在Python或IPython控制台时,当我返回输出时调用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!