[Tutor] Overriding equality tests in Python

Mitya Sirenef msirenef at lightbird.net
Sat Mar 23 05:29:04 CET 2013


On 03/23/2013 12:08 AM, Robert Sjoblom wrote:
> Hi list. I'll preface this by  saying that I am very grateful for all
 > of you, and thank you in advance to anyone that answers.
 >
 > I'm currently working on a roulette simulator, because it seemed like
 > fun. I found out I needed a way to compare two different outcomes, and
 > it was suggested to me that I should override the __eq__ and __ne__
 > methods. Said and done, I did:
 > class Outcome():
 > def __init__(self, name): #Ignoring odds for now
 > self.name = name
 >
 > def __eq__(self, other):
 > '''returns True if Outcome.name matches other.name''':
 > if self.name == other.name: return True
 > def __ne__(self, other):
 > '''returns True if Outcome.name does not match other.name'''
 > if self.name != other.name: return True
 >
 > Now, this works, as far as this is concerned:
 >>>> a = Outcome('Bob')
 >>>> b = Outcome('Ray')
 >>>> c = Outcome('Bob')
 >>>> a == b
 >>>> a == c
 > True
 >>>> a != b
 > True
 >>>>
 > 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?
 >


Firstly, in __eq__, you can do: return self.name == other.name
Second, you are right that you can also compare attributes directly. But
the meaning is different, if I'm reading your program, a == b tells me
"object a is equal to b for the purpose of this program", a.name ==
b.name tells me, name attrs are equal. a == b is also a shorter and more
readable expression. __eq__ is also used in constructs like:

if a in mylist: ...

__eq__ is probably used for other things, too; the basic idea is that it
tells Python that objects are equal, and Python can use this information
in various circumstances.

  -m



-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Each religion, by the help of more or less myth, which it takes more or
less seriously, proposes some method of fortifying the human soul and
enabling it to make its peace with its destiny.  George Santayana



More information about the Tutor mailing list