Re: Newbie Question - Overloading ==



On Mar 31, 1:23 pm, xkenneth <xkenn...@xxxxxxxxx> 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
.



Relevant Pages

  • Re: Windows File Comparing
    ... will create a signature for the file contents that you can use to ... def write_signature ... backup = FileCompObj.new ... .: Snapshot Successful ...
    (comp.lang.ruby)
  • Re: How about "pure virtual methods"?
    ... Mike Meyer wrote: ... >> The answer is that a subclass is guaranteed to have the same ... > def method: ... inspect module for signature checking helpers... ...
    (comp.lang.python)
  • Re: recursive decorator
    ... '%s' % (name, signature), ... Many thanks for your decorator routines -- no way could I have gotten this far without them to guide me! ... def bind_func: ... exec new_func in evaldict ...
    (comp.lang.python)
  • decorators, function signature, and help()
    ... After a week or so I'm finally getting accustomed to the pie-pre-def syntax. ... Consider a simple-minded decorator that doesn't care about the signature of ... def g: ... I do not see a way to preserve the signature ...
    (comp.lang.python)