faqts : Computers : Programming : Languages : Python : Language and Syntax

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

29 of 31 people (94%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

What is the difference between __repr__() and __str__()?
What is __repr__ used for?
What is __str__ used for?

Feb 29th, 2000 21:05
Nathan Wallace, unknown unknown, Gregoire Welraeds, Fredrik Lundh


according to the eff-bot:

    __repr__ should something that makes sense to a
    programmer, but not necessarily to someone else.
    (think "debugging")

    (e.g. basic types return a string literal, more complex
    types usually return some kind of descriptor, such as
    "<foo instance at 912388>" or "<open file 'foo', mode
    'r' at 918747>")

    __str__ should be used to convert the contents of an
    object to a (usually printable) string, whenever that
    makes sense (think "class design")

According to the Python reference manual, page 17 

    __repr__: called to compute the official string representation of an
    object. This should like a valid Python expression that can be used 
    to recreate an object with the same value.

    __str__: differs from repr in that in does not have to be a valid 
    python expression: a more conveniant or concise representation maybe 
    used instead.