What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter?

前端 未结 5 1184
礼貌的吻别
礼貌的吻别 2020-12-11 19:31

In the interpreter you can just write the name of an object e.g. a list a = [1, 2, 3, u\"hellö\"] at the interpreter prompt like this:

>>&         


        
5条回答
  •  暖寄归人
    2020-12-11 19:33

    The interactive interpreter will print the result of each expression typed into it. (Since statements do not evaluate, but rather execute, this printing behavior does not apply to statements such as print itself, loops, etc.)

    Proof that repr() is used by the interactive interpreter as stated by Niklas Rosenstein (using a 2.6 interpreter):

    >>> class Foo:
    ...   def __repr__(self):
    ...     return 'repr Foo'
    ...   def __str__(self):
    ...     return 'str Foo'
    ...
    >>> x = Foo()
    >>> x
    repr Foo
    >>> print x
    str Foo
    

    So while the print statement may be unnecessary in the interactive interpreter (unless you need str and not repr), the non-interactive interpreter does not do this. Placing the above code in a file and running the file will result in nothing being printed.

提交回复
热议问题