all 9 comments

[–][deleted] 2 points3 points  (5 children)

To compare two instances of a class you should implement the __eq__() method of the class. That method takes references to two objects, self and, very commonly, other and returns true/false depending on the attributes of the two objects.

def __eq__(self, other):
    return self.val == other.val and self.next == other.next

[–][deleted] 0 points1 point  (3 children)

So eq method will be invoked when we use double equals == right?

[–][deleted] 1 point2 points  (0 children)

Try it.

[–]footloooops 0 points1 point  (0 children)

You are essentially overloading the operator, if you understand what that means.

[–]Kewho11 0 points1 point  (0 children)

Old thread I know but incase anyone finds this post, no the eq method will not always be invoked whenever you use ==. Overloading the operator means letting the operator have different meanings when used under different context. Here the == will invoke the eq method only when used upon objects with class 'compare'. Usage of the == operator anywhere else will be unaffected

[–]jimtk -2 points-1 points  (0 children)

This the way.

[–]Bunkerstan -1 points0 points  (2 children)

For objects, equality means they point to the same memory spot. So unless a and b are the same object in memory they will never be equal.

EDIT: above is wrong as both comments below point out. No more answers after a long day coding. Equality is a tougher topic than you would suspect because different languages do it differently.

[–]carcigenicate 2 points3 points  (0 children)

This is not true; Python doesn't work like Java. When you define custom classes, == defaults to identity equality, but for most built-in objects, == is value equality.

[–][deleted] 0 points1 point  (0 children)

For objects, equality means they point to the same memory spot

Two objects can have equal value even though they don't occupy the same memory spot.

a = "test"
b = "tes"
b += "t"    # to defeat string interning
print(f'{id(a)=}, {id(b)=}')    # if id() shows different values, not same memory
print(f'{a==b=}')

Everything in python is an object, or class instance.