Making a python user-defined class sortable, hashable

前端 未结 4 1105
执念已碎
执念已碎 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:33

    There are a few ways of marking your object sortable. First - rich comparison, defined by a set of functions:

    object.__lt__(self, other)
    object.__le__(self, other)
    object.__eq__(self, other)
    object.__ne__(self, other)
    object.__gt__(self, other)
    object.__ge__(self, other)
    

    Also it is possible to define only one function:

    object.__cmp__(self, other)
    

    And the last should be defined if you want to define custom __hash__ function. See the doc.

提交回复
热议问题