在python中对自定义类执行集合操作 [英] performing set operations on custom classes in python

查看:59
本文介绍了在python中对自定义类执行集合操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Python 的内置集合类与我创建的自定义类一起使用.如果我愿意要创建包含自定义类实例的集合,我需要实现哪些函数才能执行测试,例如 set_a - set_b?

I'd like to use Python's built-in set class with a custom class that I've created. If I want to create sets containing instances of my custom class, what functions do I need to implement so that I can perform tests, like set_a - set_b?

推荐答案

它可以开箱即用,但是,在某些情况下,重载 __eq__, __ne____hash__.默认情况下,__eq__ 将比较对象标识.这可能不是您想要的.在这种情况下,您必须注意相等的对象具有相等的哈希值,并且理想情况下,不相等的对象具有不同的哈希值(尽管这不是必需的,它只是减少了冲突).您应该始终使用 __eq__ 实现 __ne__,除非您有特殊的理由不这样做(这样做是为了确保逻辑一致性).

It will work out of the box, however, there might be cases, when it makes sense to overload __eq__, __ne__ and __hash__. By default, __eq__ will compare for object identity. This might not be what you want. In that case, you have to take care that equal object have equal hashes, and, ideally, not equal object have different hashes (although this is not required, it merely reduces collisions). You should always implement __ne__ using __eq__, unless you have a specific reason to do otherwise (this is done to ensure logical consistency).

此外,在重载 __hash__ 时,您必须注意当对象存储在 set 中时哈希不会改变.

Also, when overloading __hash__, you have to take care that the hash does not change while the object is stored in a set.

这篇关于在python中对自定义类执行集合操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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