根据其属性为python对象生成唯一的ID
发布时间:2020-11-17 16:30:06 所属栏目:Python 来源:互联网
导读:有没有办法为 python中仅仅基于对象属性值的对象生成类似哈希的ID?例如, class test: def __init__(self, name): self.name = nameobj1 = test(a)obj2 = test(a)hash1 = magicHash(obj1)hash2 = magicHash(obj2) 我正在寻找的是ha
有没有办法为 python中仅仅基于对象属性值的对象生成类似哈希的ID?例如, class test: def __init__(self,name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) 我正在寻找的是hash1 == hash2的东西. python中是否存在类似的东西?我知道我可以测试obj1.name == obj2.name,但是我正在寻找一些可以在任何对象上使用的东西. 解决方法你的意思是这样的?使用特殊方法 __hash__
class test: def __init__(self,name): self.name = name def __hash__(self): return hash(self.name) >>> hash(test(10)) == hash(test(20)) False >>> hash(test(10)) == hash(test(10)) True (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |