Comparison methods
Rainer Deyke
root at rainerdeyke.com
Thu May 3 23:59:55 EDT 2001
"Edw88253" <none at dev.null> wrote in message
news:tf46ngropc056b at news.supernews.com...
> I had two questions about Python's comparison methods (__cmp__, __eq__,
> etc.):
>
> ================================
> Question 1:
>
> When defining __eq__ for classes, is there any "standard" result when two
> objects are compared, and one's class is a superclass of the other? I
ask,
> because initially I was defining __eq__ as:
>
> def __eq__(self, other):
> if not isinstance(other, MyClass): return 0
> return <appropriate expression>
>
> But, using that definition, a==b and b==a won't always return the same
> thing, which is presumably a Bad Thing.
>
> We could instead define __eq__ as:
>
> def __eq__(self, other):
> if not isinstance(other, MyClass): return 0
> if other.__class__ != MyClass: return 0
> return <appropriate expression>
If you want different subclasses to compare as unequal, your code fails
where '__eq__' is inherited. Try this instead:
def __eq__(self, other):
if type(other) != type(self) or other.__class__ != self.__class__:
return 0
return <appropriate expression>
There are cases where it makes more sense for instances of different
subclasses to sometimes compare as equal. In these cases, your first
'__eq__' should work provided it is never overridden by a subclass. I
cannot comment on whether your particular case is one of them.
--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games - http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor
More information about the Python-list
mailing list