Python hash() 函数

2024年9月26日 | 阅读 2 分钟

Python has() 函数用于获取对象的哈希值。 Python 使用哈希算法计算哈希值。 哈希值是整数,用于在字典查找期间比较字典键。 我们只能对这些类型进行哈希

可哈希类型:* bool * int * long * float * string * Unicode * tuple * code object

我们不能对这些类型进行哈希

不可哈希类型:* bytearray * list * set * dictionary * memoryview

签名

参数

对象:我们要获取哈希值的对象。 只有不可变类型可以被哈希。

返回

它返回对象的哈希值。

让我们看一些 hash() 函数的例子来理解它的功能。

Python hash() 函数示例 1

在这里,我们获取整数和浮点值的哈希值。 请看下面的例子。

输出

21
461168601842737174

Python hash() 函数示例 2

此函数可以应用于可迭代的值以获取哈希值。

输出

-3147983207067150749
2528502973955190484

Python hash() 函数示例 3

输出

TypeError: unhashable type: 'list'

Python hash() 函数示例 4

在这里,我们将一个新的自定义对象传递给该函数。 该函数返回此对象的哈希值。

输出

8793491452501

下一个主题Python 函数