仅实现__lt__方法是否安全?
假设我的ClassA类的实例会被放到一个数据结构里,并且我们知道会对它调用sorted()函数。调用sorted()的是别人的代码,所以我不能指定排序的方式,但我可以在ClassA中实现一些合适的方法。
在我看来,
def __lt__(self, other):
这个方法就足够了,我不需要实现其他五个左右的方法(qt、eq、le、ge、ne)。
这样做够不够呢?
1 个回答
56
PEP 8 不建议这样做。我也不推荐这种做法,因为这种编程风格很脆弱(对小的代码修改不够稳健):
相反,可以考虑使用 functools.total_ordering 这个类装饰器来完成这个工作:
@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()))