[Tutor] Overriding equality tests in Python

Robert Sjoblom robert.sjoblom at gmail.com
Sat Mar 23 05:08:06 CET 2013


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?

-- 
best regards,
Robert S.


More information about the Tutor mailing list