Python hash() 函式



Python 的 hash() 函式 如果物件是可雜湊的,則返回該物件的雜湊值。雜湊值是整數型別,用於在字典查詢期間比較字典鍵。

hash()Python 內建函式 之一,可用於不可變物件。請注意,只有不可變物件才是可雜湊的。這意味著其值不會隨時間變化的物件,例如 元組字串整數,才可以雜湊。原因是,如果物件的值可以更改,則其雜湊值也可以更改。

語法

以下是 Python hash() 函式的語法。

hash(object)  

引數

Python hash() 函式接受單個引數:

  • object − 此引數指定我們想要獲取雜湊值的 物件。

返回值

Python hash() 函式返回指定物件的雜湊值。

hash() 函式示例

練習以下示例以瞭解如何在 Python 中使用 hash() 函式。

示例:hash() 函式的使用

以下是 Python hash() 函式的一個示例。在這裡,我們定義了一個浮點值和一個整數值,並嘗試查詢這兩個值的雜湊值。

intNums = 56
output1 = hash(intNums)
floatNums = 56.2
output2 = hash(floatNums)
print(f"The hash for {intNums} is: {output1}")
print(f"The hash for {floatNums} is: {output2}")

執行上述程式後,將生成以下輸出:

The hash for 56 is: 56
The hash for 56.2 is: 461168601842745400

示例:使用 hash() 雜湊字串

字串也是可雜湊的,如果我們將字串作為引數傳遞給 hash() 函式,則它將返回其雜湊值。

varStr = "Tutorialspoint"
output = hash(varStr)
print(f"The hash for '{varStr}' is: {output}")

執行上述程式後,將獲得以下輸出:

The hash for 'Tutorialspoint' is: 887219717132446054

示例:將 hash() 與自定義物件一起使用

在以下示例中,我們將 hash() 函式應用於自定義物件。在這裡,我們將使用類的建構函式為物件分配雜湊值。

class NewClass:
   def __init__(self, value):
      self.value = value
   def __hash__(self):
      return hash(self.value)

newObj = NewClass(10)
output = hash(newObj)
print(f"The hash for given object is: {output}")

執行上述程式後,將獲得以下輸出:

The hash for given object is: 10

示例:查詢元組的雜湊值

在此示例中,我們將演示如何查詢 元組 的雜湊值。對於此操作,我們只需將元組名稱作為引數傳遞給 hash() 函式。

numsTupl = (55, 44, 33, 22, 11)
output = hash(numsTupl)
print(f"The hash for given list is: {output}")

執行上述程式後,將顯示以下輸出:

The hash for given list is: -6646844932942990143
python_built_in_functions.htm
廣告