Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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)

paulakula11 on Aug. 28, 2019

I just wanted to keep it the old fashion way:

return 'a {} car'.format(self.color)

Hector on Nov. 17, 2019

Perdon, but what does it mean ‘dunder’ in context of using it here? English is not my native. I found this…www.merriam-webster.com/dictionary/dunder

Dan Bader RP Team on Nov. 18, 2019

@Hector: dunder stands for double underscore in this context. More here in this tutorial: realpython.com/operator-function-overloading/

What about __mifflin__ ? 😃

Dan Bader RP Team on April 23, 2020

@RMS hahah nice, hadn’t heard that one before :D It’s a perfect combination. Corona quarantine, coding Python, and re-watching The Office…

Raiss Bahati on May 29, 2020

The format(self=self) part from the line of code below got me confused. What’s the logic behind it? For my part I prefer using f-strings for string formatting.

def str(self): return ‘a {self.color} car’.format(self=self)

Become a Member to join the conversation.