dan martin dan martin - 1 month ago 6
Python Question

Python - comparing 2 identical objects returns False?

I've defined a class as such:

class User:

Name = ""
Age = ""
Gender = ""

def __init__(self, var1, var2, var3):
self.Name = var1
self.Age = var2
self.Gender = var3

def __hash__(self):
return hash(self.Name)


Now when I create two identical objects:

User1 = User("Ted", "43", "M")
User2 = User("Ted", "43", "M")


And attempt to compare them:

print(User1 == User2)


It returns
False
?

Answer

The answer Mureinik provides is correct, but incomplete.

Only overriding the __eq__ method results in unexpected behavior when you are checking inequality.

For example, User1 != User2 will return True with just the __eq__ overridden.

You want to define both __eq__ and __ne__:

def __eq__(self, other):
    if isinstance(other, User):
        return self.Name == other.Name and \
           self.Age == other.Age and \
           self.Gender == other.Gender
    return NotImplemented

def __ne__(self, other):
    return not self.__eq__(other)

Now when you perform comparisons, you'll get expected results:

User1 = User("Ted", "43", "M")
User2 = User("Ted", "43", "M")
print(User1 != User2)
print(User1 == User2)

Prints:

False
True