Making a python user-defined class sortable, hashable

前端 未结 4 1107
执念已碎
执念已碎 2020-12-01 08:54

What methods need to be overridden/implemented when making user-defined classes sortable and/or hashable in python?

What are the gotchas to watch out for?

I

4条回答
  •  醉酒成梦
    2020-12-01 09:18

    Implement __lt__(self,other) method is the answer to make your class sortable.
    It can be used for not only the built-in method sorted(iterable), but also priority queue via heapq module.

    In addition, I don't like python's design, so many '__ge__', '__gt__', '__le__', '__lt__', '__ne__' methods are not intuitive at all !
    As a contrast, Java's Interface Comparable (see java doc) returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object, which is direct and friendly!

提交回复
热议问题