在本教程中,我們將借助示例了解 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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。