getattr()
先在python解释器看下getattr()的帮助 :
Help on built-in function getattr in module builtin:
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
(END)
getattr(),顾名思义就是获取对象的属性,getattr(x, ‘y’)等价于 x.y。 第三个参数可有可无,当给getattr()第三个参数时,如果对应的属性不存在,它会作为返回值返回。
看下面代码:
class Test(object):
val = 1
>>> Test.val
1
>>> getattr(Test, 'val')
1
>>> getattr(Test, 'va', 5)
5
因为val是Test的属性,所以通过getattr可以获取到val的值,而va则不是Test的属性,但我们传进了第三个参数5,所以返回5。