__str__ which is called whenever a class is turned into a string (hence the str) and __repr__ which is called whenever a representation of the class is needed. This is typically when a visual representation of the class is needed (this may sound similar to __str__ but it is subtly not as will be explained shortly). Each just returns a string, usually based on what’s in the class. What’s the difference? Well it’s actually quite simple. The repr is for when something is returned visually but not printed. For example, if you are doing python in an interactive interpreter and output an object you will see that object’s repr, but if you print the object with the print() function you will see the object’s str.
There are two rules that come out of this.
- The
__str__method should be a useful visual representation of the class instance - The
__repr__method should show what the class is, and ideally how to create this instantiation yourself. Ideally, it should be evaluatable code.
Tile and Point. Dataclasses in Python actually provide a built-in str and repr function that renders exactly what the class is and what each of the properties are.
tile produces this output.
repr because if you were to copy and paste that code into the program it would create the object it came from. But as a str method result? It’s quite verbose. However in the challenge we’re going to have a lot of these tiles and this is unnecessarily verbose for the output too. What if instead of one we had to print out 500?
We can create a str method instead that makes the output more compact and to do so, we only need to add two lines to our existing script.
tile we see the following output, which is a lot shorter and keeps the same amount of information available.