How and When to Use .__repr__()
In this lesson, you’ll see how to use a second dunder method that controls how ojects are converted to strings, the .__repr__()
:
class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
def __repr__(self):
return '__repr__ for Car'
def __str__(self):
return '__str__ for Car'
You’ll learn when __repr__
is used and how it is different from .__str__()
. The next lesson will cover the differences between the two in more detail.
00:00
In order to understand what’s going on here, I defined this class—or, kind of, redefined my Car
class. And what this new version of the Car
class does, it actually has a .__repr__()
and a .__str__()
implementation.
00:16
Now, those implementations are just dummy implementations that are going to tell us what’s going on behind the scenes. So, if something calls .__repr__()
behind the scenes, we’re going to get '__repr__ for Car'
as a result, and if something calls .__str__()
, we’re going to get '__str__ for Car'
as a result.
00:30
So now, we can walk through to the same example again and do a print(my_car)
. And you can see here, okay, it called the .__str__()
function.
00:39
We could also go through the .format()
example again—you can see it called the .__str__()
function. And now, if we do my_car
and just inspect that, we can see here that it’s actually called .__repr__()
for the Car
.
00:50
And another way to force this is to call the built-in repr()
function, and then that’s going to do the right thing and call the correct .__repr__()
implementation for this.
01:03
Usually, you just want to use the str()
and repr()
helpers for that.
01:09 Now, of course, the big question is, “Okay, so now we have these two—what’s actually the difference between them, or what’s the different use cases where you would use them?”
Become a Member to join the conversation.