在 python 中,內置函數hash()
用於獲取給定對象的哈希值。為了在字典查找時比較字典關鍵字,使用這些整數哈希值。實際上hash()
方法調用的是對象的 __hash__()
方法。
Hashable 類型: bool int long float string Unicode tuple code 對象
不可散列類型:位元組數組列表集合字典*內存視圖
**hash(object)** #Where object can beinteger, 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))
pers 'Adam')
print(hash(person))
輸出:
The hash is:
3785419240612877014
原創文章,作者:OARFB,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/317879.html