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

后端 未结 2 1343
萌比男神i
萌比男神i 2020-12-11 17:43

For example,

python
>> x = 1
>> x
1

I\'m curious about what method/function on x is returning 1. I\'m asking beca

2条回答
  •  醉话见心
    2020-12-11 18:17

    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
    

    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".

    [__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.

提交回复
热议问题