Python getattr() 函数
用于返回一个对象属性值。
class A(object):
bar = 1
a = A()
getattr(a, 'bar') # 获取属性 bar 值
结果:1
getattr(a, 'bar2') # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值
结果:3