哈希函数
哈希函数哈希函数可以把给定的数据转换成固定长度的无规律数值,转换后的无规律数值可以作为数据摘要应用于各种各样的场景。
Python 中实现哈希函数的是 hash() 函数,它会调用对象的 __hash__() 魔法方法。
>>> hex(hash('123')) # 将转化后的哈希值(十进制整数)转化为十六进制整数
'-0x2df4c3642922ec63'
>>> hex(hash('123456789qwertyuiop'))
'-0x3b0b4fb7601afabf'
>>> hex(hash(1234567890987654321))
'0x112210f4b16c1cb1'
>>> hex('123'.__hash__())
'-0x2df4c3642922ec63'
>>> hex('123456789qwertyuiop'.__hash__())
'-0x3b0b4fb7601afabf'
>>> hex((1234567890987654321).__hash__())
'0x112210f4b16c1cb1' 补充一点:{:10_248:}
要实现unhashble的类,应该把类的__hash__属性设为None
再补充一个哈希冲突的例子:{:10_248:}>>> hash(10**10000)
809130080075442044
>>> hash(809130080075442044)
809130080075442044 本帖最后由 永恒的蓝色梦想 于 2020-5-13 13:55 编辑
def hash(obj,/):
if obj.__hash__ is None:
raise TypeError(f"unhashable type: '{obj.__class__.__name__}'")
temp=obj.__hash__()
if isinstance(obj,int):
return temp.__hash__()
raise TypeError("__hash__ method should return an integer")
页:
[1]