1

I am trying to understand how to check equality of class instances.

Let's say I have a class as follows:

class Car(object):
    def __init__(self):
        self._color = None

I instanciate two objects as follows :

car1 = Car()
car1._color = 'red'
car2 = Car()
car2._color = 'red'

The two objects having exactly the same attributes, I naively thaught that:

print(car1 == car2)

would print True , which is not the case.

What is happening here?

I did find a solution to check equality:

print(car1.__dict__ == car2.__dict__)

which does print True.

Was that in fact the simplest thing to do?

Matina G
  • 1,452
  • 2
  • 14
  • 28

0 Answers0