Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Learn how to utilize Python's built-in method, `__str__`.
The method we're going to work with
in this video is Dunder string.
0:00
This method controls how your
objects are represented as a string.
0:05
When you print out
an instance of your class,
0:11
you get something like
this in the console.
0:13
Not the most useful message, right?
0:19
Well, with Dunder string,
you can tell Python what to do here.
0:22
Let's add a Dunder string
method to our class.
0:27
This will override what is currently
happening with what we want to happen
0:30
instead.
0:34
I'm going to place my method
right here after the Dunder init.
0:37
I like to keep my Dunders together.
0:45
Inside of my method,
I'm going to return an f string
0:54
with the make model and
year of the car inside.
1:00
Now when I run the file,
Instead of that car object at message,
1:17
we instead get the make, model, and year
of our car printed out to the console.
1:24
This also handles any time our instance
is converted to a string, Like so.
1:31
Now try it out on your own by creating
a class and giving it a Dunder string
1:51
method, and then create an instance and
print it out to see your message
1:56
You need to sign up for Treehouse in order to download course files.
Sign up