cmp

Mark McEahern markjunk at mceahern.com
Thu Dec 27 11:21:33 EST 2001


> Perhaps then could someone explain to me how one compares classes
> useing the == operator, or indeed if this bad programming practice.

By overloading the __cmp__ method.  Don't confuse the return value of
__cmp__ with whether or not the result of the comparison is that the two
instances being compared are equal.  Examine this sample and note that
__cmp__ isn't merely used to determine equality.  It is also used to
determine sort order.

class foo:

    def __init__(self, bar):
        self.bar = bar

    def __cmp__(self, other):
        if self.bar == other.bar:
            return 0
        elif self.bar < other.bar:
            return -1
        else:
            return 1

    def __repr__(self):
        return "<foo bar='%s'/>" % self.bar

a = foo(1)
b = foo(2)
c = foo(3)
d = foo(1)

list = [b, c, a]

print "before sorting:"
print list
print

list.sort()

print "after sorting:"
print list
print

print "a == d: %s" % (a == d)





More information about the Python-list mailing list