hasattr(object,name):判断object对象里是否有name属性或者方法,有=>True,否=>False!
>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> hasattr(t, "name") #判断对象有name属性True>>> hasattr(t, "run") #判断对象有run方法True>>>
getattr(object,name[,default]):获取object对象里的name属性或者方法,属性存在=>打印,不存在=>默认值(默认值可选),如果是对象里的方法,返回的是方法的内存地址,加()就可运行!
>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> getattr(t, "name") #获取name属性,存在就打印出来。'xiaohua'>>> getattr(t, "run") #获取run方法,存在就打印出方法的内存地址。>>>> getattr(t, "run")() #获取run方法,后面加括号可以将这个方法运行。'HelloWord'>>> getattr(t, "age") #获取一个不存在的属性。Traceback (most recent call last): File " ", line 1, in AttributeError: test instance has no attribute 'age'>>> getattr(t, "age","18") #若属性不存在,返回一个默认值。'18'>>>
setattr(object,name,values):给对象的属性赋值,若属性不存在,则先创建再赋值!
>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> hasattr(t, "age") #判断属性是否存在False>>> setattr(t, "age", "18") #为属相赋值,并没有返回值>>> hasattr(t, "age") #属性存在了True>>>
------------------------------------------------------------------------------------------------------------低调内涵不华丽的分割线--------------------------------------------------------------------------------------------------------------------------
一种综合的用法是:判断一个对象的属性是否存在,若不存在就添加该属性。
>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> getattr(t, "age") #age属性不存在Traceback (most recent call last): File "", line 1, in AttributeError: test instance has no attribute 'age'>>> getattr(t, "age", setattr(t, "age", "18")) #age属性不存在时,设置该属性'18'>>> getattr(t, "age") #可检测设置成功'18'>>>