custom sorting and __cmp__

Kristian Ovaska kristian.ovaska at helsinki.fi
Sun Nov 30 12:04:06 EST 2003


Lee Harr <missive at frontiernet.net>:
>Should I be catching comparisons to objects that do not have
>my 'level' attribute and falling back to id comparison?

I usually solve it like this:

class A:
    def __init__(self, level):
        self.level = level

    def __cmp__(self, other):
        if isinstance(other, A):
            return cmp(self.level, other.level)
        else:
            return -1

-- 
Kristian Ovaska - http://www.cs.helsinki.fi/u/hkovaska/




More information about the Python-list mailing list