Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Why do we need to use __str__ method?

Why do we need to use _str method when we have an empty list, like in this example:

class Car:
    def __init__(self, make, year):
        self.make=make
        self.year=year

    def __str__(self):
        return "{} {}".format(self.make, self.year)

class Dealership:
    def __init__(self):
        self.cars=[]

    def __iter__(self):
        yield from self.cars

    def add_cars (self, car):
        self.cars.append(car)

car_one=Car("Ford", 2000)
my_dealership=Dealership()
my_dealership.add_cars(car_one)
for car in my_dealership:
    print(car)

In this case, for example, when we have list of cars, we do not need to use that method:

class Dealership:
    def __init__(self):
        self.cars=["Ford Fusion","Honda Civic"]

    def __iter__(self):
        yield from self.cars

my_dealership=Dealership()
for car in my_dealership:
    print(car)

What is the difference ( why do we need str method in the first example, but not in the second?)

1 Answer

Yo HP!

You use a str function/method to "overload" the default way the print function would display a Car class instance.

Without it,

print(myCar)

Would print something like:

<__main__.Car object at 0x7fa9ca802438>

By using the str function as coded here,

print(myCar)

Would print more something like

Honda 2020

Instead

I hope that helps.

Stay safe and happy coding!