[Tutor] Overriding equality tests in Python

Alan Gauld alan.gauld at btinternet.com
Sat Mar 23 10:25:51 CET 2013


On 23/03/13 04:08, Robert Sjoblom wrote:

> However, if I were to create a class without the __eq__ and __ne__
> definitions, what is to prevent me from doing: a.name == b.name ? Or
> am I missing something in my implementation of the overrides? Is there
> a reason why I shouldn't do .name comparisons?

Yes, polymorphism.

If you have a function that takes a collection of different types of 
object and you want to compare them you don't want that function to need 
to know how to compare every possible type of object (including the ones 
you haven't written yet). The classic example is a sort
function

L1 = [1,3,5,4,2,6,8]
L2 - [ Outcome(...),Outcome(...)...Outcome()]

my lists = [L1,L2]

for lst in mylists: lst.sort()

That last line can only work sensibly if the lists contain objects that 
know how to compare themselves.

There are many other places where you could be processing mixed objects 
and want to apply an equality test as part of the algorithm. Hiding the 
details of the representation of the object inside a method is what OOP 
is all about. That is what allows us to write code that uses objects 
rather than the data hidden inside those objects.

Welcome to the world of abstract data types :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list