Python中文网

python hash()

cnpython327

在 Python 中,hash() 函数是将一个对象(比如字符串、元组、数字等)转化为一个 hash 值,该值是一个整数。该函数的作用是将不同的对象映射到唯一的固定大小的整数值。在本文中,我们将介绍 hash() 函数的使用方法及其示例代码。

hash() 函数的使用方法

hash() 函数的语法如下:

 pythonCopy code
 hash(object)

其中,object 是要进行哈希的对象。hash() 函数会返回一个整数,该整数代表该对象的哈希值。哈希值在不同的 Python 解释器或不同的解释器版本中可能会不同。

Python 中可以哈希的对象包括:

  • 整数、浮点数、布尔值等基本数据类型

  • 字符串、元组等不可变类型

  • frozenset 类型

  • 实现了 __hash__()__eq__() 方法的自定义类

需要注意的是,某些类型的对象无法哈希,例如列表、字典等可变类型,尝试对它们进行哈希操作会抛出 TypeError 异常。

hash() 函数的示例代码

下面是一些 hash() 函数的示例代码,以便更好地理解该函数的用法和作用。

示例 1:基本数据类型

 pythonCopy code
 # 对整数进行哈希
 print(hash(123))  # 输出: 123
 print(hash(456))  # 输出: 456
 ​
 # 对浮点数进行哈希
 print(hash(3.14))  # 输出: 642090810131880899
 print(hash(2.71))  # 输出: 9185994163557165572
 ​
 # 对布尔值进行哈希
 print(hash(True))  # 输出: 1
 print(hash(False))  # 输出: 0

示例 2:不可变类型

 pythonCopy code
 # 对字符串进行哈希
 print(hash("hello"))  # 输出: 1620418033250695930
 print(hash("world"))  # 输出: -3319911820860656766
 ​
 # 对元组进行哈希
 print(hash((1, 2, 3)))  # 输出: 529344067295497451
 print(hash((4, 5, 6)))  # 输出: 2760675060059472006
 ​
 # 对 frozenset 进行哈希
 print(hash(frozenset([1, 2, 3])))  # 输出: -536870920
 print(hash(frozenset([4, 5, 6])))  # 输出: -536870921

示例 3:自定义类

 pythonCopy code
 class Person:
     def __init__(self, name, age):
         self.name = name
         self.age = age
 ​
     def __hash__(self):
         return hash((self.name, self.age))
 ​
     def __eq__(self, other):
         return self.name == other.name and self.age == other.age
 ​
 p1 = Person("Tom", 20)
 p2 = Person("Tom", 20)
 p3 = Person("Jerry", 25

上一篇:没有了

下一篇:python help()