Python的hasattr() getattr() setattr() 函数使用方法详解

hasattr(object, name)
判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。
需要注意的是name要用括号括起来

>>> class test():
        name="vincent"
        def foo(self):
                return "I am foo."
   
>>> t=test()
>>> hasattr(t, "name") #判断对象有name属性
True
>>> hasattr(t, "foo")  #判断对象有foo方法
True
>>>
View Code

getattr(object, name[,default])
获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。
需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,
可以在后面添加一对括号。

>>> class test():
        name="xiaohua"
        def run(self):
                return "HelloWord"
   
>>> t=test()
>>> getattr(t, "name") #获取name属性,存在就打印出来。
'vincent'
>>> getattr(t, "foo")  #获取f00方法,存在就打印出方法的内存地址。
<bound method test.run of <__main__.test instance at 0x0287C654>>
>>> getattr(t, "foo")()  #获取foo方法,后面加括号可以将这个方法运行。
'I am foo.'
>>> getattr(t, "age")  #获取一个不存在的属性。
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age","23")  #若属性不存在,返回一个默认值。
'23'
>>>

setattr(object, name, values)
给对象的属性赋值,若属性不存在,先创建再赋值。

>>> class test():
        name="vincent"
        def foo(self):
                return "I am foo."
   
>>> t=test()
>>> hasattr(t, "age")   #判断属性是否存在
False
>>> setattr(t, "age", "23")   #为属相赋值,并没有返回值
>>> hasattr(t, "age")    #属性存在了
True
>>>

一种综合的用法是:判断一个对象的属性是否存在,若不存在就添加该属性。

>>> class test():
        name="vincent"
        def foo(self):
                return "I am foo."
   
>>> t=test()
>>> getattr(t, "age")    #age属性不存在
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age", setattr(t, "age", "23")) #age属性不存在时,设置该属性
'23'
>>> getattr(t, "age")  #可检测设置成功
'23'
>>>
原文地址:https://www.cnblogs.com/zijue/p/13952583.html