Classes and OOP I

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:

Python
Output

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():

Python

Now printing the object gives a readable result:

Python
Output

What will be the output?

Python

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:

Python
Output

You can also use format specifiers inside the f-string. You learned these in Strings II.

Use :.2f to show exactly two decimal places:

Python
Output

What will be the output?

Python

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:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python