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

前端 未结 5 1178
礼貌的吻别
礼貌的吻别 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:56

    Typing an object into the terminal calls __repr__(), which is for a detailed representation of the object you are printing (unambiguous). When you tell something to 'print', you are calling __str__() and therefore asking for something human readable.

    Alex Martelli gave a great explanation here. Other responses in the thread might also illuminate the difference.

    For example, take a look at datetime objects.

    >>> import datetime
    >>> now = datetime.datetime.now()
    

    Compare...

    >>> now
    Out: datetime.datetime(2011, 8, 18, 15, 10, 29, 827606)
    

    to...

    >>> print now
    Out: 2011-08-18 15:10:29.827606
    

    Hopefully that makes it a little more clear!

提交回复
热议问题