String representations of class instances str and repr methods

suggest change

A note about implemeting both methods

When both methods are implemented, it’s somewhat common to have a __str__ method that returns a human-friendly representation (e.g. “Ace of Spaces”) and __repr__ return an eval-friendly representation.

In fact, the Python docs for repr() note exactly this:

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.

What that means is that __str__ might be implemented to return something like “Ace of Spaces” as shown previously, __repr__ might be implemented to instead return Card('Spades', 1)

This string could be passed directly back into eval in somewhat of a “round-trip”:

object -> string -> object

An example of an implementation of such a method might be:

def __repr__(self):
    return "Card(%s, %d)" % (self.suit, self.pips)

Notes

[1] This output is implementation specific. The string displayed is from cpython.

[2] You may have already seen the result of this str()/repr() divide and not known it. When strings containing special characters such as backslashes are converted to strings via str() the backslashes appear as-is (they appear once). When they’re converted to strings via repr() (for example, as elements of a list being displayed), the backslashes are escaped and thus appear twice.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


String representations of class:
* String representations of class instances str and repr methods

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
125 String representations of class
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve