如果对象是可哈希的,则 Python hash() 函数将返回对象的哈希值。哈希值是整数类型,用于在字典查找期间比较字典键。
hash() 是 Python 内置函数之一,适用于不可变对象。请注意,只有不可变对象是可哈希的。这意味着可以对其值不能随时间变化的对象(例如 Tuples、String 和 Integer)进行哈希处理。原因是,如果对象的值可以更改,则其哈希值也可以更改。
语法
以下是 python hash() 函数的语法。
hash(object)
参数
python hash() 函数接受单个参数 -
- object − 此参数指定我们想要其哈希值的对象。
返回值
python hash() 函数返回指定对象的哈希值。
hash() 函数示例
练习以下示例以了解 hash() 函数在 Python 中的使用:
示例:使用 hash() 函数
以下是 python hash() 函数的示例。在此,我们定义了一个 float 和一个整数值,并尝试找到这两个值的哈希值。
intNums = 56
output1 = hash(intNums)
floatNums = 56.2
output2 = hash(floatNums)
print(f"The hash for {intNums} is: {output1}")
print(f"The hash for {floatNums} is: {output2}")
在执行上述程序时,将生成以下输出 -
The hash for 56 is: 56
The hash for 56.2 is: 461168601842745400
The hash for 56.2 is: 461168601842745400
示例:使用 hash() 对字符串进行哈希处理
字符串也是可哈希的,如果我们将字符串作为参数传递给 hash() 函数,那么它将返回其哈希值。
varStr = "qikepu"
output = hash(varStr)
print(f"The hash for '{varStr}' is: {output}")
以下是执行上述程序得到的输出 -
The hash for 'qikepu' is: 887219717132446054
示例:将 hash() 与 Customize Object 一起使用
在以下示例中,我们将对自定义对象应用 hash() 函数。在这里,我们将使用类的 constructor 为对象分配一个哈希值。
class NewClass:
def __init__(self, value):
self.value = value
def __hash__(self):
return hash(self.value)
newObj = NewClass(10)
output = hash(newObj)
print(f"The hash for given object is: {output}")
通过执行上述程序获得以下输出 -
The hash for given object is: 10
示例:查找元组的哈希值
在此示例中,我们将演示如何查找元组的哈希值。对于此操作,我们只需将元组名称作为参数传递给 hash() 函数。
numsTupl = (55, 44, 33, 22, 11)
output = hash(numsTupl)
print(f"The hash for given list is: {output}")
上述程序在执行时显示以下输出 -
The hash for given list is: -6646844932942990143