So again, it’s overridden with a method defined as a dunder method—beginning and ending with two underscores—the
.__str__() method. And when we use it, we actually have to explicitly state that we want to use the
str() (string) method.
Here, I have added to my
Car class the
.__str__() method. It has to have a parameter, so you refer to the calling object. And it’s returning an f-string, formatted string, built up of the car’s color, model, and year.
So this format is going to match the same one that you saw for the Java class. And so this gives us a convenient way, now that we have defined it. So let’s see how that works. I will import the
f"My car is a"… Now, this is a little bit different. We’re going to use this like a function call, not a method call. We’ll say string—well,
str()—and then we put the name of our object as the parameter.
Again, not quite what we’re used to with method calls, but this is the syntax that
.__str__() and a lot of the other default methods use. You don’t use the underscores. You use it as a function call.
And so how that might look—it might look the exact same way as your
.__str__() method. But if your
.__str__() method is phrased nicely for user output, you might have a more technical version in your
Become a Member to join the conversation.