[Tutor] Overriding equality tests in Python
Dave Angel
davea at davea.name
Sat Mar 23 13:03:11 CET 2013
On 03/23/2013 12:08 AM, Robert Sjoblom wrote:
You already got lots of good answers. But I want to explicitly point
out a bug in your code (2 places) that was only indirectly mentioned.
<SNIP>
> 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
Here your method returns either True or None. You never supply a return
value of False, you just let the default None get returned. For most
purposes that will work, but it's a problem waiting to happen.
In this particular case, it's easiest to just return the expression:
self.name == other.name
which already has a value of True or False. But if the function were
more complex, you'd want to make sure that all paths through it will
return the value you desire, and not the default None.
def my_method(self, other):
'''returns True if Outcome.name matches other.name and False
otherwise''':
if self.name == other.name: return True
return False
--
DaveA
More information about the Tutor
mailing list