Representing Objects as Strings with __str__
In this lesson, you will learn how to provide human-readable string representations of your custom objects using the __str__ magic method.
The Default Representation
When you create a class and try to print an instance of it, Python gives you a somewhat mysterious output:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
my_book = Book("The Great Gatsby", "F. Scott Fitzgerald")
print(my_book)
# Output: <__main__.Book object at 0x7f8b1c0a2d90>
That output is helpful for the computer (telling you where the object lives in memory), but it is not very useful for you. When you are debugging or logging your application, you want to see the actual data inside the object.
Customizing with __str__
You can take control of this by defining the __str__ magic method inside your class. This method must return a string. Whenever you call print() on your object or convert it to a string using str(), Python will automatically run this method.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"'{self.title}' by {self.author}"
my_book = Book("The Great Gatsby", "F. Scott Fitzgerald")
print(my_book)
# Output: 'The Great Gatsby' by F. Scott Fitzgerald
Why Use __str__?
Defining __str__ makes your code much friendlier to work with. If you are logging application state, instead of seeing cryptic memory addresses, your logs will contain meaningful summaries of your objects. It makes your code self-documenting and significantly easier to debug because you can see exactly what an object contains at a glance. Just remember that __str__ should always return a string and should be designed to be readable for end-users or developers.
Key Takeaway: By defining the __str__ method in your class, you create a clear, human-readable string representation of your object that improves both code readability and debugging efficiency.