object, name
[
, default
]
)
-
Return the value of the named attributed of
object.
name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar')
is equivalent tox.foobar
. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. -
-
- 例子:
-
#!/ usr/bin/ python#-*- conding utf-8 -*-
class Tests(object): #定义类aaa = '10' #定义变量
def test(self): #定义类的方法testb = 20return b
if __name__ == "__main__" :t = Tests() #实例化
snap1 = getattr(t, 'test' )() #获取对象中test方法,并执行snap2 = getattr(t, 'aaa' , 'default' ) #获取对象中相应的值,如果没有,则使用defaultsnap3 = getattr(t, ' bbb' , 'default' ) #获取对象中相应的值,如果没有,则使用defaultprint 'snap1=' ,snap1print 'snap2=' ,snap2print 'snap3=' ,snap3
输出如下snap1= 20snap2= 10snap3= default