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 Basic Object-Oriented Python Emulating Built-ins __iter__

Sam Appleton
Sam Appleton
3,832 Points

Using (self,*cars) instead of (self,cars) for multiple instances

I tried using *cars and it returns the car object ID instead of the model year and make. Any ideas on how I would get the loop to use the def str method?

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

def iter(self): yield from self.cars

def add_car(self, *car): self.cars.append(car)

car_one = Car('Model T', 1908) car_two = Car('Phantom', 2020, 'Rolls Royce')

my_dealership = Dealership() my_dealership.add_car(car_one, car_two)

for car in my_dealership: print(car)

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

You look like you understand Python class, nice job!

All you need is a little bit of Python magic "dunder" methods to get your job done:

__init__, __str__, __iter__

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

    def __str__(self):
        return f"{self.make} {self.year} {self.brand}"        

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

    def __iter__(self):
        yield from self.cars

    def add_car(self, *cars):
        for car in cars:
            self.cars.append(car)

car_one = Car('Model T', 1908 )
car_two = Car('Phantom', 2020, 'Rolls Royce')

my_dealership = Dealership()
my_dealership.add_car(car_one, car_two)

for car in my_dealership:
    print(car)