使python用户定义的类可排序,hashable [英] Making a python user-defined class sortable, hashable
问题描述
当使用户定义的类在python中可排序和/或哈希时,需要重写/实现什么方法?
需要注意的是什么? / p>
我输入 dir({})
到我的解释器中获取内置dicts的方法列表。其中,我假设我需要实现一些子集
['__ cmp__','__eq__','__ge__' '__gt__','__hash__','__le__','__lt__','__ne__']
有什么区别,其中的方法必须实现Python3而不是Python2?
我几乎发布了这个评论
为了使你的项目可排序,他们只需要实现 __ lt __
。这是内置排序使用的唯一方法。
其他比较或 functools.total_ordering
为了使您的项目具有哈希值,您需要实现 __ hash __
其他人指出。您还应以兼容方式实现 __ eq __
- 等效的项目应该散列相同。
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 type dir({})
into my interpreter to get a list of methods on built-in dicts. Of those, I assume I need to some implement some subset of
['__cmp__', '__eq__', '__ge__', '__gt__', '__hash__', '__le__', '__lt__', '__ne__']
Is there a difference in which methods must be implemented for Python3 as opposed to Python2?
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.
这篇关于使python用户定义的类可排序,hashable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!