在 python 中对自定义类执行集合操作
我想将 Python 的内置 set 类与我创建的自定义类一起使用。如果我愿意 要创建包含自定义类实例的集合,我需要实现哪些函数才能执行测试,例如 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以开箱即用,但是,在某些情况下,重载
__eq__
,__ne__
和__hash__
。默认情况下,__eq__
将比较对象标识。这可能不是您想要的。在这种情况下,您必须注意相等的对象具有相等的哈希值,并且理想情况下,不相等的对象具有不同的哈希值(尽管这不是必需的,它只是减少冲突)。您应该始终使用__eq__
实现__ne__
,除非您有特定原因不这样做(这样做是为了确保逻辑一致性)。此外,在重载 __hash__ 时,您必须注意当对象存储在
set
中时哈希不会更改。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).Also, when overloading
__hash__
, you have to take care that the hash does not change while the object is stored in aset
.