Is it safe to just implement __lt__ for a class that will be sorted?

前端 未结 1 1911
北荒
北荒 2020-12-14 15:04

Suppose instances of my ClassA will end up in a data structure and we know sorted() will be called on it. It\'s someone else\'s code that\'ll call sorted() so I can\'t spec

相关标签:
1条回答
  • 2020-12-14 15:53

    PEP 8 recommends against this practice. I also recommend against it because it is a fragile programming style (not robust against minor code modifications):

    Instead, consider using the functools.total_ordering class decorator to do the work:

    @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()))
    
    0 讨论(0)
提交回复
热议问题