使 Python 用户定义的类可排序、可散列 [英] Making a python user-defined class sortable, hashable

查看:31
本文介绍了使 Python 用户定义的类可排序、可散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中使用户定义的类可排序和/或可散列时,需要覆盖/实现哪些方法?

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

需要注意哪些问题?

我在解释器中输入 dir({}) 以获取内置字典的方法列表.其中,我假设我需要实现一些

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__']

Python3 和 Python2 必须实现的方法有什么不同吗?

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.

要使您的项目可排序,它们只需要实现 __lt__.这是内置排序使用的唯一方法.

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

其他比较或 functools.total_ordering 仅当您确实想在类中使用比较运算符时才需要.

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

为了使您的项目可散列,您可以像其他人指出的那样实施 __hash__.您还应该以兼容的方式实现 __eq__ -- 等效的项目应该散列相同.

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 用户定义的类可排序、可散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆