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("qikepu")
setattr(nameObj, "location", "Hyderabad")
print("Location is set to:", nameObj.location)
当我们运行上述程序时,它会产生以下结果——
Location is set to: Hyderabad
示例:使用 setattr() 函数修改属性的值
setattr() 函数还可用于修改现有属性的值。在下面的代码中,我们将使用新的值修改之前设置的 location 属性值。
class qikepu:
def __init__(self, location):
self.location = location
locationObj = qikepu("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
After modifying location is set to: Noida
示例:使用 setattr() 函数动态添加类方法
在 setattr() 函数的帮助下,我们可以动态添加类方法。在下面的代码中,我们定义了一个名为 “employee” 的方法,并将定义的方法添加到指定的类中。
class qikepu:
pass
def employee():
return "Present"
employeeObj = qikepu()
setattr(employeeObj, "isPresent", employee)
print("Status of employee is set to:", employeeObj.isPresent())
上述代码的输出如下 -
Status of employee is set to: Present