如果对象具有哈希值,则 hash()
方法会返回该哈希值。哈希值只是用于在字典查找时快速比较字典键的整数。
示例
text = 'Python Programming'
# compute the hash value of text
hash_value = hash(text)
print(hash_value)
# Output: -966697084172663693
hash() 语法
hash()
方法的语法是
hash(object)
hash() 参数
hash()
方法接受一个参数
- object - 要返回哈希值的对象(整数、字符串、浮点数)
hash() 返回值
hash()
方法返回对象的哈希值。
示例 1:Python 中 hash() 如何工作?
# 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()?
hash()
方法只适用于元组等不可变对象。
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels))
输出
The hash is: -695778075465126279
hash() 如何适用于自定义对象?
如上所述,hash()
方法内部调用 __hash__()
方法。因此,任何对象都可以通过重写 __hash__()
来获得自定义哈希值。
但为了实现正确的哈希,__hash__()
应该始终返回一个整数。并且,必须同时实现 __eq__()
和 __hash__()
方法。
以下是正确重写 __hash__()
的情况。
__eq__() | __hash__() | 描述 |
---|---|---|
已定义(默认) | 已定义(默认) | 如果保持原样,所有对象都比较不相等(除了它们本身) |
(如果可变)已定义 | 不应定义 | 可哈希集合的实现要求键的哈希值是不可变的 |
未定义 | 不应定义 | 如果未定义 __eq__() ,则不应定义 __hash__() 。 |
已定义 | 未定义 | 类实例不能用作可哈希集合。__hash__() 隐式设置为 None 。如果尝试检索哈希,会引发 TypeError 异常。 |
已定义 | 从父类继承 | __hash__ = |
已定义 | 不想哈希 | __hash__ = None 。如果尝试检索哈希,会引发 TypeError 异常。 |
示例 3:通过重写 __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
另请阅读