Newbie Question - Overloading ==

Jean-Paul Calderone exarkun at divmod.com
Mon Mar 31 13:41:32 EDT 2008


On Mon, 31 Mar 2008 10:23:24 -0700 (PDT), xkenneth <xkenneth 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.
>
>I have a sneaky feeling I'm doing something completely unpythonic
>here.

Give this a look:

  http://jcalderone.livejournal.com/32837.html

Jean-Paul



More information about the Python-list mailing list