hasattr(obj,name):是判断一个对象里面是否包含name属性,或name方法,返回bool类型值,如果存在返回True,否则返回False

>>> class ClsTest():
name='xiaoyanzi'
def run(self):
return 'this is helloword'

>>>ct=ClsTest()
>>> hasattr(ct,'name')  #判断这个对象里面是否有name属性
True
>>> hasattr(ct,'run') #判断这个对象里面是否有run方法
True
>>>

 

getattr(obj,name[,default])

获取对象中的属性或者方法,如果存在就打印出来,如果不存在,就打印出来默认值,默认值是可选的,

如果是返回对象的方法,需要在最后加个括号,不加括号返回的是“方法的内存地址”,

>>> class ClsTest():
name='xiaoyanzi'
def run(self):
return 'this is helloword'


>>> ct=ClsTest()
>>> getattr(ct,'name') #获取这个对象里面的属性值
'xiaoyanzi'

>>> getattr(ct,'run')() #获取这个对象里面的方法,getattr(ct,'run')(),加了括号就是执行了这个方法
'this is helloword'
>>> getattr(ct,'run') #获取这个对象里面的方法,没有执行就是返回一个内存地址
<bound method ClsTest.run of <__main__.ClsTest object at 0x0000000003831A90>>
>>>

setattr(obj,name,values)

给对象的属性赋值,如果此属性不存在,会先创建,然后再赋值

>>> class ClsTest():
name='xiaoyanzi'
def run(self):
return 'this is helloword'


>>> ct=ClsTest()
>>> hasattr(ct,'age') #先判断一下对象中有没有age这个属性,返回false说明age属性不存在
False
>>> setattr(ct,'age','22')#调用setattr()这个方法后,在判断一下
>>> hasattr(ct,'age')#此时返回结果为True,说明如果此属性不存在,会先创建,然后再赋值
True
>>>

posted on 2018-03-12 14:55  追梦-等待  阅读(83)  评论(0编辑  收藏  举报