getattr() 函数在 Python 中起什么作用?
pythonserver side programmingprogramming
Python getattr()
getattr() 方法返回对象命名属性的值。如果未找到,则返回提供给函数的默认值。
语法
getattr() 方法的语法是 −
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)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

