String Conversion Workarounds and .to_string()
In this lesson, you’ll see common workarounds to the problem highlighted in the last lesson. You’ll see two ways in which string conversions inside a class can be done. The first way is to reach into the class and print out attributes directly and the second method is to use a custom .to_string()
method to print out a string representing the class.
00:00 Now, there’s a common workaround that I see some people apply. For example, they start printing out the class attributes directly. And sure—that works, you can do that.
00:13
We can kind of pry that class apart and reach in and take out the .color
and the .mileage
here—that works. And then what I see some people do is they would kind of go ahead and do their own to_string()
method, right?
00:27 And then that would print directly or return a string representing the class. But there is a convention inside Python that handles all of that, so you don’t have to come up with your own ways to do that because there’s actually preexisting conventions on how to do that.
00:44
So, I want to explain to you how that works. Basically what you’re going to learn today is how the dunder .__str__()
and dunder .__repr__()
methods work in Python. This is going to be a highly useful thing.
00:57 This is a common interview question. So, you know, watching this tutorial could literally pay you money in the future, so stay tuned if you don’t know how this stuff works.
Become a Member to join the conversation.