31. Python hash()

发布时间:2023-12-08

Python hash()

更新:2022-07-24 11:11 在 Python 中,内置函数hash()用于获取给定对象的哈希值。为了在字典查找时比较字典关键字,使用这些整数哈希值。实际上hash()方法调用的是对象的 __hash__() 方法。 Hashable 类型:

  • bool
  • int
  • long
  • float
  • string
  • Unicode
  • tuple
  • code 对象
    不可散列类型:
  • 字节数组
  • 列表
  • 集合
  • 字典
  • 内存视图
hash(object)  # Where object can be integer, string, float etc.

哈希()参数:

接受单个参数。相等的数值将具有相同的哈希值,而与它们的数据类型无关。

参数 描述 必需/可选
目标 要返回其哈希值的对象(整数、字符串、浮点) 可选择的

散列()返回值

hash()方法返回对象的哈希值(如果有)。对象采用自定义__hash__()方法,它将返回值截断为 Py_ssize_t 的大小。

投入 返回值
目标 哈希值

Python 中hash()方法的示例

示例hash()在 Python 中是如何工作的?

# hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:', hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python'))

输出:

Hash for 181 is: 181
Hash for 181.23 is: 530343892119126197
Hash for Python is: 2230730083538390373

示例 2:不可变元组对象的hash()

# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels))

输出:

The hash is: -695778075465126279

示例 3:通过覆盖__hash__()为自定义对象设置__hash__()

class Person:
    def __init__(self, age, name):
        self.age = age
        self.name = name
    def __eq__(self, other):
        return self.age == other.age and self.name == other.name
    def __hash__(self):
        print('The hash is:')
        return hash((self.age, self.name))
person = Person(23, 'Adam')
print(hash(person))

输出:

The hash is:
3785419240612877014