How and When to Use __str__

Give Feedback

In this lesson, you’ll see one Pythonic way to convert Python objects into strings by using __str__. You’ll learn what __str__ means as well and also learn how to use it in a Python class:

class Car:
    def __init__(self, color, mileage):
        self.color = color
        self.mileage = mileage

    def __str__(self):
        return 'a {self.color} car'.format(self=self)

Comments & Discussion

Become a Member to join the conversation.