Python getattr() 函数用于访问对象的属性。如果未找到指定的属性,则返回默认值。
与用于为对象属性赋值的 setattr() 函数不同,getattr() 函数用于获取指定对象的值。
setattr() 是内置函数之一,您无需导入任何模块即可使用它。
语法
以下是 Python getattr() 函数的语法。
getattr(object, attribute, default)
参数
以下是 Python getattr() 函数的参数 -
- object − 此参数指定需要搜索其属性的对象。
- attribute − 此参数表示我们要获取其值的属性。
- default − 此参数是可选的,它指定当指定属性不存在时将返回的值。
返回值
Python getattr() 函数返回给定对象的 named 属性的值。如果未找到该属性,则返回默认值。
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() 函数,我们访问父类中包含的 attribute 的值。
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
Ansh
30
Present