新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonhash()
在 python 中,內(nèi)置函數(shù)hash()用于獲取給定對象的哈希值。為了在字典查找時比較字典關(guān)鍵字,使用這些整數(shù)哈希值。實(shí)際上hash()方法調(diào)用的是對象的 __hash__() 方法。

Hashable 類型: bool int long float string Unicode tuple code 對象
不可散列類型:字節(jié)數(shù)組列表集合字典*內(nèi)存視圖
**hash(object)** #Where object can beinteger, string, float etc.
哈希()參數(shù):
接受單個參數(shù)。相等的數(shù)值將具有相同的哈希值,而與它們的數(shù)據(jù)類型無關(guān)。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 目標(biāo) | 要返回其哈希值的對象(整數(shù)、字符串、浮點(diǎn)) | 可選擇的 |
散列()返回值
hash()方法返回對象的哈希值(如果有)。對象采用自定義__hash__()方法,它將返回值截?cái)酁?Py_ssize_t 的大小。
| 投入 | 返回值 | | 目標(biāo) | 哈希值 |
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__()為自定義對象設(shè)置__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 新聞標(biāo)題:創(chuàng)新互聯(lián)Python教程:Pythonhash()
文章URL:http://www.dlmjj.cn/article/dhieoho.html


咨詢
建站咨詢
