Loading video player…

How and When to Use .__str__()

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)

00:00 Okay. So, to ease into this with a simple example, I took the same Car class and I added a .__str__() method here. So, the dunder methods are methods that start with a double underscore (__)—it’s just kind of been shortened to dunder.

00:14 Some people refer to them as magic methodsa lot of people don’t like that because they’re not really supposed to be magical in any way. They’re just supposed to be, well, a Python convention. And the dunder, or the double underscore (__), marks them as a core Python thing, so classes are not supposed to actually define their own dunder methods because it could conflict with Python features in the future.

00:37 And so this is just a way to kind of namespace these things a little bit, just by a naming convention, kind of keeping them separate a little bit, just like the .__init__() method.

00:47 But you know—total sidetrack here. So what I’ve done here is I added a .__str__() method. And basically what I did here—whenever that method is called, it just returns the .color of the Car and kind of tells us it’s a Car.

01:00 So just to show you an example here—again, I’m going to create

01:05 the same Car. And now when I print this Car

01:12 I actually get a completely different result, right? So this time I get a red carwhich is the result of this .__str__() method—instead of this crazy string with the object address in memory. However, when I just inspect this object, I still get the memory address in the previous result.

01:30 So, inspecting the Car object still gives the same result, but when I printed the Car object, I got this different result based on the .__str__() method.

01:42 The way you would actually convert an object to string—if you wanted to force that or make that happen—

01:50 you would just use the built-in str() method, and then that is internally going to do the right thing and call the .__str__() method, and it’s going to give you back the right result.

02:01 Now, all of these functions that deal with text representations for objects, like the print() function—they are going to do that internally.

02:09 They’re going to call the str() function for you. And it would be the same with a format string, for example. So if you do this, then this would also call .__str__() and just give you the result.

02:20 But the key thing is here that by convention, if you add a .__str__() method, then it’s going to do a lot of good for you in controlling how your object is represented as a string. So it’s the Pythonic way to do this, which is kind of the Holy Grail, right? Now, still what you’re seeing here was that when I inspected the my_car object in the console, I still got the same result.

02:46 So there seems to be different ways to convert your objects into strings. The first one we just learned about—it’s called dunder .__str__().

02:55 And now the second one is called dunder .__repr__(). Let’s talk about what .__repr__() does and how it’s different to .__str__().

Avatar image for paulakula11

paulakula11 on Aug. 28, 2019

I just wanted to keep it the old fashion way:

return 'a {} car'.format(self.color)
Avatar image for Hector

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

Avatar image for Dan Bader

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__ ? 😃

Avatar image for Dan Bader

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…

Avatar image for Raïss Bahati

Raïss 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.