Making a python user-defined class sortable, hashable

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

    There isn't any difference between Python 2 and 3.

    For sortability:

    You should define comparision methods. This makes your items sortable. Generally, you shouldn't prefer __cmp__().

    I usually use functools.total_ordering decorator.

    functools.total_ordering(cls) Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

    The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.

    You should be careful that your comparison methods do not have any side effects. (change any of the values of the object)

    For hashing:

    You should implement __hash__() method. I think the best way is returning hash(repr(self)), so your hash would be unique.

提交回复
热议问题