Python 3 中的可比类 [英] Comparable classes in Python 3
本文介绍了Python 3 中的可比类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 3 中使类具有可比性的标准方法是什么?(例如,通过 id.)
What is the standard way of making a class comparable in Python 3? (For example, by id.)
推荐答案
为了让类具有可比性,你只需要实现 __lt__
并用 functools.total_ordering
.如果可能,您还应该提供 __eq__
方法.这提供了其余的比较运算符,因此您不必自己编写任何一个.
To make classes comparable, you only need to implement __lt__
and decorate the class with functools.total_ordering
. You should also provide an __eq__
method if possible. This provides the rest of the comparison operators so you don't have to write any of them yourself.
这篇关于Python 3 中的可比类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文