这个类直接实现__lt__方法排序是安全的吗?

2024-04-24 08:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的ClassA的实例将以一个数据结构结束,我们知道将对它调用sorted()。其他人的代码将调用sorted(),因此我不能指定排序函数,但我可以实现任何适合于ClassA的方法。

在我看来

def __lt__(self, other):

已经足够了,我不需要实现其他五种左右的方法(qt、eq、le、ge、ne)。

这足够吗?


Tags: 实例方法函数代码ltselfle数据结构
1条回答
网友
1楼 · 发布于 2024-04-24 08:54:18

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()))

相关问题 更多 >