使用对象id作为Python中对象的散列 [英] Using object id as a hash for objects in Python

查看:123
本文介绍了使用对象id作为Python中对象的散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用对象 id 作为散列键(通过 __ hash __ )能够能够明智地使用为程序的单个实例散列另外可变的对象?使用对象属性会更好,但它们都是可变的,并且可以改变。

在我看到设置实例,我想知道是否明智。

解决方案

是的,只要您还定义 __ eq __ (大概 __ ne __ ! - )与此一致。 IOW,没关系,只要你认为 a == b 完全相同就是b ! - )

Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change.

This occurred to me while looking at Sets of instances and I'm wondering if it's wise.

解决方案

Yes, as long as you also define __eq__ (and presumably __ne__!-) consistently with that. IOW, it's fine, as long as you're fine with a==b meaning exactly the same as a is b!-)

这篇关于使用对象id作为Python中对象的散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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