2024-04-24 08:54:18 发布
网友
假设我的ClassA的实例将以一个数据结构结束,我们知道将对它调用sorted()。其他人的代码将调用sorted(),因此我不能指定排序函数,但我可以实现任何适合于ClassA的方法。
在我看来
def __lt__(self, other):
已经足够了,我不需要实现其他五种左右的方法(qt、eq、le、ge、ne)。
这足够吗?
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()))
PEP 8建议不要这样做。我也建议不要使用它,因为它是一种脆弱的编程风格(对微小的代码修改并不健壮):
相反,请考虑使用functools.total_ordering类装饰器来完成以下工作:
相关问题 更多 >
编程相关推荐