Making a python user-defined class sortable, hashable

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

    I almost posted this as a comment to the other answers but it's really an answer in and of itself.

    To make your items sortable, they only need to implement __lt__. That's the only method used by the built in sort.

    The other comparisons or functools.total_ordering are only needed if you actually want to use the comparison operators with your class.

    To make your items hashable, you implement __hash__ as others noted. You should also implement __eq__ in a compatible way -- items that are equivalent should hash the same.

提交回复
热议问题