getattr()函数在Python中做什么?

Python getattr()

getattr()方法返回对象的命名属性的值。如果找不到,它将返回提供给该函数的默认值。

语法

getattr()method的语法是-

getattr(object, name[, default])

getattr()方法可以采用多个参数-

getattr()方法返回-

给定对象的命名属性的值

默认值,如果找不到命名属性

AttributeError异常,如果找不到命名属性并且未定义默认属性

示例

class Male:
    age = 21
    name = "Abel"
x = Male()print('The age is:', getattr(x, "age"))
print('The age is:', x.age)

输出结果

这给出了输出

('The age is:', 21)
('The age is:', 21)