Python hasattr() 函式



Python hasattr() 函式 用於檢查物件是否包含指定的屬性。如果屬性存在,則返回 True,否則返回 False。

在訪問屬性之前,可以使用此函式確保屬性存在,這有助於防止執行時錯誤。hasattr() 函式Python 中的內建函式之一

要獲取和設定 屬性,可以使用 getattr()setattr() 函式。

語法

Python hasattr() 函式的語法如下所示:

hasattr(object, attribute)

引數

以下是 python hasattr() 函式的引數:

  • object - 此引數指定需要檢查其命名屬性的物件。

  • attribute - 此引數表示要在指定物件中搜索的字串。

返回值

Python hasattr() 函式返回一個布林值。

hasattr() 函式示例

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

示例:hasattr() 函式的使用

以下是 Python hasattr() 函式的示例。在這裡,我們定義了一個類並例項化了其物件,並嘗試驗證它是否包含指定的屬性。

class Car:
   wheels = 4

transport = Car()
output = hasattr(transport, "wheels") 
print("The car has wheels:", output)

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

The car has wheels: True

示例:檢查繼承類的屬性

hasattr() 函式也可以輕鬆檢查繼承的屬性。在下面的程式碼中,我們定義了一個父類及其子類。然後,使用 hasattr() 函式,我們檢查子類是否能夠繼承其父類的屬性。

class Car:
   wheels = 4

class Tata(Car):
   fuelType = "Petrol"

newCar = Tata()
output = hasattr(newCar, "wheels") 
print("The new car has wheels:", output)

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

The new car has wheels: True

示例:當屬性不存在時使用 hasattr() 函式

如果給定物件中不存在指定的屬性,則 hasattr() 函式將返回 false。這裡,傳遞的屬性不屬於任何定義的類。因此,結果將為 False。

class Car:
    wheels = 4

class Tata(Car):
    fuelType = "Petrol"

newCar = Tata()
output = hasattr(newCar, "wings") 
print("The new car has wheels:", output)

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

The new car has wheels: False

示例 4

在以下示例中,我們使用 hasattr() 函式來驗證給定的方法是否在指定的類中定義。

class AI:
   def genAI(self):
      pass

chatGpt = AI()
output = hasattr(chatGpt, "genAI")
print("The chat GPT is genAI:", output)

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

The chat GPT is genAI: True
python_built_in_functions.htm
廣告