Elegant compare

Jason Friedman jsf80238 at gmail.com
Sun Aug 11 11:17:13 EDT 2013


> This is a hard question to answer, because your code snippet isn't
> clearly extensible to the case where you have ten attributes. What's the
> rule for combining them? If instance A has five attributes less than
> those of instance B, and five attributes greater than those of instance
> B, which wins?

Yes, my code snippet was too short, I should have said:

class my_class:
    def __init__(self, attr1, attr2, attr3):
        self.attr1 = attr1 #string
        self.attr2 = attr2 #string
        self.attr3 = attr3 #string
    def __lt__(self, other):
        if self.attr1 < other.attr1:
            return True
        elif self.attr2 < other.attr2:
            return True
        else:
            return self.attr3 < other.attr3

Chris's answer is actually perfectly adequate for my needs.
Thank you Steve and Chris.



More information about the Python-list mailing list