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 __eq__

Chris Jullienne
Chris Jullienne
2,458 Points

Can't get equal result on __eq__ video within Basic Object-Oriented Python

Could someone check my code below to see why i'm not getting equal when comparing car_one and car_two?

class Car:
    # Class Attributes
    wheels = 4
    doors = 2
    engine = True

    # The Initializer
    def __init__(self, model, year, make='Ford', gas=100):
        # Instance Attributes
        self.make = make
        self.model = model
        self.year = year
        self.gas = gas
        # instance attributes don't have
        # to be passed in
        self.is_moving = False

    def __str__(self):
        return f'{self.make} {self.model} {self.year}'

    def use_gas(self):
        self.gas -= 50
        if self.gas <= 0:
            return False
        return True

    def stop(self):
        if self.is_moving:
            print('The car has stopped.')
            self.is_moving = False
        else:
            print('The car has already stopped.')

    def go(self, speed):
        if self.use_gas():
            if not self.is_moving:
                print('The car starts moving.')
                self.is_moving = True
            print(f'The car is going {speed}.')
        else:
            print("You've run out of gas!")
            self.stop()


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

    def __iter__(self):
        yield from self.cars

    def __eq__(self,other):
      return self.make == other.make and self.model == other.model

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


car_one = Car("Ka", 2020)
car_two = Car("Ka", 2020)
car_three = Car("Fiesta", 2000)

if car_one == car_two:
  print('equal')
else:
  print('not equal')



#my_dealership = Dealership()
#my_dealership.add_car(car_one)
#my_dealership.add_car(car_two)
#my_dealership.add_car(car_three)
#for car in my_dealership:
 #  print(car)

1 Answer

Andy Hughes
Andy Hughes
8,479 Points

Chris Jullienne

Hi Chris,

Check the location of your eq function. At the moment, it is sitting outside of your Car class. I've just tested the code with it in the correct place and it works fine. :)

Hope that helps.