__lt__ instead of __cmp__

后端 未结 5 2032
暖寄归人
暖寄归人 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:25

    (Edited 6/17/17 to take comments into account.)

    I tried out the comparable mixin answer above. I ran into trouble with "None". Here is a modified version that handles equality comparisons with "None". (I saw no reason to bother with inequality comparisons with None as lacking semantics):

    
    class ComparableMixin(object):
    
        def __eq__(self, other):
            if not isinstance(other, type(self)): 
                return NotImplemented
            else:
                return not self

提交回复
热议问题