在本教程中,我们将借助示例了解 Python hash() 方法。
hash()
方法返回一个对象的哈希值(如果它有一个)。哈希值只是用于在字典快速查找期间比较字典键的整数。
示例
text = 'Python Programming'
# compute the hash value of text
hash_value = hash(text)
print(hash_value)
# Output: -966697084172663693
hash() 语法
用法:
hash(object)
参数:
hash()
方法采用单个参数:
- object- 要返回其哈希值的对象(整数、字符串、浮点数)
返回:
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() 用于不可变元组对象?
hash()
方法仅适用于不可变对象,如 tuple 。
# 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__() | 说明 |
---|---|---|
已定义(默认) | 已定义(默认) | 如果保持原样,所有对象比较不相等(除了它们自己) |
(如果可变)已定义 | 不应定义 | hashable collection的实现要求key的hash值是不可变的 |
没有定义的 | 不应定义 | 如果未定义__eq__() ,则不应定义__hash__() 。 |
Defined | 没有定义的 | 类实例将不能用作可散列集合。 __hash__() 隐式设置为 None 。如果尝试检索哈希,则会引发 TypeError 异常。 |
Defined | 从父级保留 | __hash__ = <ParentClass>.__hash__ |
Defined | 不想散列 | __hash__ = None 。如果尝试检索哈希,则会引发 TypeError 异常。 |
示例 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
注意:您不必实施__eq__()
哈希的方法,因为它是默认为所有对象创建的。
相关用法
- Python hash()用法及代码示例
- Python hashlib.sha3_256()用法及代码示例
- Python hashlib.sha3_512()用法及代码示例
- Python hashlib.blake2s()用法及代码示例
- Python hashlib.blake2b()用法及代码示例
- Python hashlib.sha3_224()用法及代码示例
- Python hashlib.shake_256()用法及代码示例
- Python hashlib.shake_128()用法及代码示例
- Python hashlib.sha3_384()用法及代码示例
- Python hasattr()用法及代码示例
- Python statistics harmonic_mean()用法及代码示例
- Python OpenCV haveImageReader()用法及代码示例
- Python help()用法及代码示例
- Python html.escape()用法及代码示例
- Python html.unescape()用法及代码示例
- Python math hypot()用法及代码示例
- Python hex()用法及代码示例
- Python torch.distributed.rpc.rpc_async用法及代码示例
- Python torch.nn.InstanceNorm3d用法及代码示例
- Python pandas.arrays.IntervalArray.is_empty用法及代码示例
注:本文由纯净天空筛选整理自 Python hash()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。