Python setattr() 函式



**Python setattr() 函式**允許我們為指定物件的屬性設定新值。它用於建立新屬性併為其設定值。它是內建函式之一,無需任何模組即可使用。

語法

以下是 Python setattr() 函式的語法:

setattr(object, attribute, value)

引數

Python setattr() 函式接受以下引數:

  • object - 此引數表示一個物件。

  • attribute - 它表示屬性名稱。

  • value - 它指定要設定的值。

返回值

Python setattr() 函式返回 None 值。

setattr() 函式示例

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

示例:setattr() 函式的使用

以下示例演示了 Python setattr() 函式的使用。在這裡,我們正在建立一個類並設定該類的新的屬性。

class OrgName:
   def __init__(self, name):
      self.name = name

nameObj = OrgName("TutorialsPoint")
setattr(nameObj, "location", "Hyderabad")  
print("Location is set to:", nameObj.location) 

執行上述程式時,將產生以下結果:

Location is set to: Hyderabad

示例:使用 setattr() 函式修改屬性的值

setattr() 函式也可以用來修改現有屬性的值。在下面的程式碼中,我們用新的值修改了之前設定的 location 屬性的值。

class TutorialsPoint:
   def __init__(self, location):
      self.location = location

locationObj = TutorialsPoint("Hyderabad")
print("Before modifying location is set to:", locationObj.location) 
setattr(locationObj, "location", "Noida")  
print("After modifying location is set to:", locationObj.location)

以下是上述程式碼的輸出:

Before modifying location is set to: Hyderabad
After modifying location is set to: Noida

示例:使用 setattr() 函式動態新增類方法

藉助 setattr() 函式,我們可以動態新增類方法。在下面的程式碼中,我們定義了一個名為“employee”的方法,並將定義的方法新增到指定的類。

class TutorialsPoint:
   pass
    
def employee():
   return "Present"

employeeObj = TutorialsPoint()
setattr(employeeObj, "isPresent", employee)  
print("Status of employee is set to:", employeeObj.isPresent())

上述程式碼的輸出如下:

Status of employee is set to: Present
python_built_in_functions.htm
廣告