Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 27,918 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)