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
本文介绍了Python中的getattr函数,用于获取对象的属性值。通过实例演示了如何使用该函数,包括存在属性和不存在属性时的返回值。此外,还展示了如何通过默认参数处理未找到属性的情况。
2387

被折叠的 条评论
为什么被折叠?



