Newbie Question - Overloading ==

Carl Banks pavlovevidence at gmail.com
Mon Mar 31 14:31:23 EDT 2008


On Mar 31, 1:23 pm, xkenneth <xkenn... at gmail.com> wrote:
> So i generally write quite a few classes, and in most I need to
> overload the == operator.
>
> If i have two classes, like below:
>
> Class A:
> attribute a
> attribute b
>
> Class B:
> attribute a
> attribute c
>
> So if I've overloaded their respective __eq__ functions, and I want to
> test whether or not the individual classes attributes are equal, the
> code might look something like this:
>
> class A:
>     def __eq__(self,other):
>          return self.a == other.a and self.b == other.b
>
> class B:
>     def __eq__(self,other):
>         return self.a == other.a and self.c == other.c
>
> Now obviously, if I test an instance of either class equal to each
> other, an attribute error will be thrown, how do I handle this? I
> could rewrite every __eq__ function and catch attribute errors, but
> that's tedious, and seemingly unpythonic. Also, I don't want an
> attribute error thrown whenever two classes are compared that don't
> have the same attributes.

What do you want to happen?

What I'd suggest, without knowing more about your problem, is to
define a method to return some kind of signature to compare instead.
For instance, you could create a dict of the attributes you care
about, and return that.  The comparison


class A(object):
    def comparison_signature(self):
        return { 'a': self.a, 'b': self.b }
    def __eq__(self,other):
        return self.comparison_signature() ==
other.comparison_signature()

class B(object):
    def comparison_signature(self):
        return { 'a': self.a, 'c': self.c }
    def __eq__(self,other):
        return self.comparison_signature() ==
other.comparison_signature()


This I suspect would handle your problem gracefully, assuming that
objects of different types should be considered not equal and have a
different set of attributes in the signature.

For extra credit, you can factor the __eq__ method into a parent class
and inherit the comparison in A and B.


Carl Banks



More information about the Python-list mailing list