container.___le___ can use only <=?

Arnaud Delobelle arnodel at googlemail.com
Sat Dec 15 09:25:56 EST 2007


On Dec 15, 2:05 pm, ceru... at tds.net wrote:

> My reasoning is (I hope) that the container ought to support every
> comparison operation supported by the contained objects. This can be
> ensured by being careful in the implementation.
>

If you're traversing two containers in parallel to compare them then
you could do something like:

class LarchTree:
    ...
    def compare(self, other, cmp):
        # Same code as your original __gt__ but
        # with cmp(x, y) instead of x > y

    def __lt__(self, other):
        return self.compare(other, operator.lt)

    def __gt__(self, other):
        return self.compare(other, operator.gt)

    # etc...


This way the LarchTree object doesn't interpret the comparison
operators, just passes them on to its elements.

--
Arnaud




More information about the Python-list mailing list