掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網(wǎng)交流
在 python 中,內置函數(shù)hash()用于獲取給定對象的哈希值。為了在字典查找時比較字典關鍵字,使用這些整數(shù)哈希值。實際上hash()方法調用的是對象的 __hash__() 方法。

Hashable 類型: bool int long float string Unicode tuple code 對象
不可散列類型:字節(jié)數(shù)組列表集合字典*內存視圖
**hash(object)** #Where object can beinteger, string, float etc.
接受單個參數(shù)。相等的數(shù)值將具有相同的哈希值,而與它們的數(shù)據(jù)類型無關。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 目標 | 要返回其哈希值的對象(整數(shù)、字符串、浮點) | 可選擇的 |
hash()方法返回對象的哈希值(如果有)。對象采用自定義__hash__()方法,它將返回值截斷為 Py_ssize_t 的大小。
| 投入 | 返回值 | | 目標 | 哈希值 |
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
hash()? # tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels))
輸出:
The hash is: -695778075465126279
__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 
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網(wǎng)交流