The __str__ Method
When you print a list, Python shows its contents neatly. When you print your own object, you get something like <__main__.Dog object>. The __str__ method lets you control what appears.
When you print a list, Python shows its contents. When you print one of your own objects, you get something unhelpful. Let's fix that.
Look what happens when you print a custom object with no special setup:
Not useful. Python is showing the default representation: the class name and a memory address. You can change this by defining a __str__ method.
The __str__ method must return a string. Python calls it automatically when you use print() or str():
Now printing the object gives a readable result:
What will be the output?
Remember f-strings from the Strings II series? They are perfect for building readable representations with multiple attributes.
Combine multiple attributes into a single string:
You can also use format specifiers inside the f-string. You learned these in Strings II.
Use :.2f to show exactly two decimal places:
What will be the output?
Calling str() on an object also triggers __str__. That means you can use the result as a normal string.
Convert to string and use it in other expressions:
What will be the output?
What will be the output?
What will be the output?