Newbie Question - Overloading ==

xkenneth xkenneth at gmail.com
Mon Mar 31 13:23:24 EDT 2008


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.

Thanks!

Regards,
Kenneth Miller




More information about the Python-list mailing list