Tutorial Study Image

Python hash()

在 Python 中,内置函数 hash() 用于获取给定对象的哈希值。在字典查找时,这些整数哈希值用于比较字典键。实际上,hash() 方法会调用对象的 __hash__() 方法。

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

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


hash(object) #Where object can be integer, string, float etc.

hash() 参数:

接受一个参数。相等数值的哈希值将相同,无论其数据类型如何。

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

hash() 返回值

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

输入 返回值
对象 哈希值

Python 中 hash() 方法的示例

示例 1: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))
 pers 'Adam')
print(hash(person))
 

输出

The hash is:
3785419240612877014