Python id() 函式



Python 的 id() 函式 用於獲取物件的唯一識別符號。此識別符號是一個數值(更具體地說是一個整數),對應於物件在Python 直譯器中任何給定時間的記憶體地址。

ID 在物件建立時分配,每個物件都分配一個唯一的 ID 用於標識。每次執行程式時,都會分配不同的 ID。但是,也有一些例外。此函式是內建函式之一,不需要匯入任何內建模組。

語法

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

id(object)

引數

python id() 函式接受單個引數:

  • object − 此引數指定要返回其 ID 的物件。

返回值

Python id() 函式返回整數型別的唯一 ID。

id() 函式示例

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

示例:id() 函式的使用

以下是一個 Python id() 函式的示例。在這裡,我們嘗試查詢整數的值的 ID。

nums = 62
output = id(nums)
print("The id of number is:", output)

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

The id of number is: 140166222350480

示例:使用 id() 函式獲取物件的唯一 ID

以下示例演示如何顯示字串的唯一 ID。我們只需要將字串名稱作為引數傳遞給 id() 函式。

strName = "Tutorialspoint"
output = id(strName)
print("The id of given string is:", output)

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

The id of given string is: 139993015982128

示例:使用 id() 函式獲取和比較兩個物件的 ID

不能為兩個物件分配相同的 ID。在此示例中,我們建立兩個物件,然後檢查它們的 ID 是否相等。如果它們相等,則程式碼將返回 true,否則返回 false。

numsOne = 62
numsTwo = 56
resOne = id(numsOne)
resTwo = id(numsTwo)
print("The id of the first number is:", resOne)
print("The id of the second number is:", resTwo)
equality = id(numsOne) == id(numsTwo)
print("Is both IDs are equal:", equality)

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

The id of the first number is: 140489357661000
The id of the second number is: 140489357660808
Is both IDs are equal: False

示例:為物件分配新的唯一 ID

類物件也會分配唯一的識別符號或 ID。在這裡,我們說明了這一點。

class NewClass:
   pass

objNew = NewClass()
output = id(objNew)
print("The id of the specified object is:", output)

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

The id of the specified object is: 140548873010816
python_built_in_functions.htm
廣告