Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Writing the .__str__()

00:00 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.

00:12 Define .__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.

00:38 So, f"The {self.color} car has {self.mileage} miles."

00:43 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.

01:39 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.”

01:53 All right, let’s try this out. I’ll press F5 and run it. And then let me create this blue_car again.

02:04 And now I should be able to just print(blue_car)

02:08 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().

02:32 That is, it’s a Car that is "red", and it has 30_000 miles. And now I should be able to print(red_car) as well.

02:43 And I get the nice output. The red car has 30,000 miles. And that’s it. We solved the challenge. What’s the code that you came up with?

Become a Member to join the conversation.