gsa*_*wal 6 python hash dictionary
我在python字典中使用自定义对象作为键.这些对象有一些默认的哈希和eq方法定义,这些方法在默认比较中使用但是在某些功能中我需要使用不同的方法来比较这些对象.那么有没有办法为这个特定的函数覆盖或传递一个新的比较器来进行这些键比较.
更新:我的类有以下类型的功能(这里我不能编辑哈希方法,它会在其他地方影响很多)
class test(object):
def __init__(self,name,city):
self.name=name
self.city=city
def __eq__(self,other):
hash_equality= (self.name==other.name)
if(not hash_equality):
#check with lower
return (self.name.lower()==other.name.lower())
def __hash__(self):
return self.name.__hash__()
my_dict={}
a=test("a","city1")
my_dict[a]="obj1"
b=test("a","city2")
print b in my_dict #prints true
c=test("A","city1")
print c in my_dict #prints false
print c in my_dict.keys() #prints true
# my_dict[c] throw error
Run Code Online (Sandbox Code Playgroud)
这是正常的功能.但是在一个特定的方法中,我想覆盖/或传递一个新的自定义比较器,其中新的哈希代码就像
def __hash__(self):
return self.name.lower().__hash__()
Run Code Online (Sandbox Code Playgroud)
所以c in my_dict返回ture
要么 my_dict[c] will return "obj1"
很抱歉这么多的更新.
像在排序中我们可以将自定义方法作为比较器传递,有没有办法在这里做同样的事情.
| 归档时间: |
|
| 查看次数: |
5390 次 |
| 最近记录: |