python中的hasattr,getattr,setattr使用总结

在工作学习中,遇到这三个函数,一直记不到,现在总结如下

hasattr(object, name)
判断一个对象里面是否有name属性或者name方法,返回bool值,有name返回True, 否则返回False。

>>> class demo():
...     name="ganiner"
...     def run(self):
...             return "ganiner hello"
...
>>> t=demo()
>>> hasattr(t,"name")
True
>>> hasattr(t,"run")
True
>>> hasattr(t,"runner")
False

getattr(object, name[,default])
获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。

>>> class demo():
...     name="ganiner"
...     def run(self):
...             return "ganiner hello"
...
>>> t=demo()
>>> getattr(t,"run")
<bound method demo.run of <__main__.demo object at 0x0000015CB31C2460>>
>>> getattr(t,"run")()
'ganiner hello'

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

>>> t=demo()
>>> hasattr(t,"age")
False
>>> setattr(t,"age","18")
>>> hasattr(t,"age")
True

 

上一篇:7段数码管绘制


下一篇:【转载】Phoenix