Python getattr() 函式



**Python getattr() 函式** 用於訪問物件的屬性。如果未找到指定的屬性,則返回預設值。

setattr() 函式(用於為物件的屬性賦值)不同,**getattr()** 函式用於獲取指定物件的屬性值。

**setattr()** 是內建函式之一,您無需匯入任何模組即可使用它。

語法

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

getattr(object, attribute, default)

引數

以下是 Python **getattr()** 函式的引數:

  • **object** - 此引數指定需要搜尋其屬性的物件。

  • **attribute** - 此引數表示要獲取其值的屬性。

  • **default** - 此引數是可選的,它指定在指定屬性不存在時將返回的值。

返回值

Python **getattr()** 函式返回給定物件的命名屬性的值。如果找不到該屬性,則返回預設值。

getattr() 函式示例

練習以下示例以瞭解 Python 中 **getattr()** 函式的使用方法。

示例:getattr() 函式的使用

以下是 Python getattr() 函式的一個示例。在這裡,我們定義了一個類並例項化了它的物件,然後嘗試檢索指定屬性的值。

class Car:
   wheels = 4

transport = Car()
output = getattr(transport, "wheels") 
print("How many wheels does the car have:", output)

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

How many wheels does the car have: 4

示例:使用 getattr() 獲取繼承物件的屬性值

使用 getattr() 函式,我們還可以檢索繼承的屬性的值。在下面的程式碼中,我們定義了一個父類及其子類。然後,使用 getattr() 函式,我們訪問父類中包含的屬性的值。

class Car:
   wheels = 4

class Tata(Car):
   fuelType = "Petrol"

newCar = Tata()
output = getattr(newCar, "wheels") 
print("The number of wheels the new car has:", output)

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

The number of wheels the new car has: 4

示例:使用 getattr() 獲取方法的值

在以下示例中,我們使用 `getattr()` 函式來訪問指定類中給定方法的值。

class AI:
   def genAI(self):
      return "This is your prompt"

chatGpt = AI()
output = getattr(chatGpt, "genAI")
print("The chat GPT wrote:", output())

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

The chat GPT wrote: This is your prompt

示例:使用 getattr() 獲取類屬性的值

我們還可以使用 `getattr()` 函式訪問給定屬性的值,如下例所示。

info = ["name", "emp_id", "status"]
class Emp:
   def __init__(self, name, emp_id, status):
      self.name = name
      self.emp_id = emp_id
      self.status = status

emp = Emp("Ansh", 30, "Present")
print("The information of Employee:")
for i in info:
   print(getattr(emp, i))

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

The information of Employee:
Ansh
30
Present
python_built_in_functions.htm
廣告