Writing the .__str__()
I already built a minimal solution that has these two instance attributes and a small
Car class in the last lesson. But now we’re going to add on the
.__str__() method to print the output more nicely.
.__str__(). Again, it takes
self as the parameter. And now we’re just going to return an f-string that I will make similar to what I did previously. Maybe we’ll change it a bit, but some output like that looks pretty good. Only it’s not going to be
blue_car, but here I need to reference generically to the instance itself.
And so one thing you may have noticed is that the output here is kind of, like, stuck together.
20000 is a bit hard to read. And what I did earlier when putting in the number, I put this underscore in between here—that’s a valid way of writing an integer in Python.
00:58 You can use underscores in there. They’re going to get ignored. This is really just visually for you as a human or for other people reading your code to make it easier to understand what big numbers you’re working with.
01:10 But there’s also something similar for output. There’s something called the string mini-language. You can add it directly inside of an f-string by putting a colon and then you can put specific parameters to change how the variable gets printed.
01:28 In this case, I’m just going to put a comma here. And that means that Python is going to take whatever number is here and put commas in the appropriate places. So it’s going to be every three digits.
So it’s going to display as
20,000. And that’s these two little pieces of information. So the colon starts the string mini-syntax, and then the comma that says, “To an integer, every three digits, put a comma.”
and I get this. Instead of
__main__.Car object at memory address, I get
The blue car has 20,000 miles. And you can see also the comma in here that separates three digits from two others. That’s because of the colon comma that I put over here. All right, and I should create a second, a
red_car. I’m going to say
red_car = Car().
Become a Member to join the conversation.