__lt__ instead of __cmp__

后端 未结 5 2006
暖寄归人
暖寄归人 2020-11-28 02:05

Python 2.x has two ways to overload comparison operators, __cmp__ or the \"rich comparison operators\" such as __lt__. The rich comparison overloads are said to be

5条回答
  •  独厮守ぢ
    2020-11-28 02:32

    To simplify this case there's a class decorator in Python 2.7+/3.2+, functools.total_ordering, that can be used to implement what Alex suggests. Example from the docs:

    @total_ordering
    class Student:
        def __eq__(self, other):
            return ((self.lastname.lower(), self.firstname.lower()) ==
                    (other.lastname.lower(), other.firstname.lower()))
        def __lt__(self, other):
            return ((self.lastname.lower(), self.firstname.lower()) <
                    (other.lastname.lower(), other.firstname.lower()))
    

提交回复
热议问题