Section 13.10 Converting an Object to a String
When we’re working with classes and objects, it is often necessary to print an object (that is, to print the state of an object). Consider the example below.
The
print
function shown above produces a string representation of the Rectangle r
. The default functionality provided by Python tells you that r
is an object of type Rectangle
(along with the memory address of the object when running the program in a real Python environment). However, it does not tell you anything about the specific state of the point.We can improve on this representation if we include a special method called
__str__
. Notice that this method uses the same naming convention as the constructor: two underscores before and after the name. Python commonly uses this double-underscore naming technique for special methods.The
__str__
method is responsible for returning a string representation as defined by the class creator. In other words, you as the programmer, get to choose what a Rectangle
should look like when it gets printed. In this case, we have decided that the string representation will include the values of width
and height
as well as some identifying text. The __str__
method must return
a string. In the following code, we return an f-string (as described in Section 7.10) for convenience.When we run the program above you can see that the
print
function now shows the string that we chose.Now, you ask, don’t we already have an
str
type converter that can turn our object into a string? Yes, we do! And doesn’t print
automatically use this when printing things? Yes again!But, as we saw earlier, these automatic mechanisms do not do exactly what we want. Python provides many default implementations for methods that we as programmers will probably want to change. When a programmer changes the meaning of a special method we say that we override the method. Note also that the
str
type converter function uses whatever __str__
method we provide.