待深入理解
https://blog.csdn.net/weixin_42233629/article/details/82261547
简单理解
hasattr(object, name)
判断object里面是否有name属性或者name方法,返回bool值,有name特性返回True, 否则返回False。
class Test(object):
name = "test"
def run(self):
return "run run run"
t = Test()
hasattr(t, "name")
Out[3]: True
hasattr(t, "run")
Out[4]: True
getattr(object, name,[default])
获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。
需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址
getattr(t, "name")
Out[5]: 'test'
getattr(t, "age")
Traceback (most recent call last):
Out[6]:File "<ipython-input-6-a0866cb37b6b>", line 1, in <module>
getattr(t, "age")
AttributeError: 'Test' object has no attribute 'age'
getattr(t, "age", "18")
Out[7]: '18'
getattr(t, "run")
Out[8]: <bound method Test.run of <__main__.Test object at 0x00000174F19AE2B0>>
setattr(object, name, values)
给对象的属性赋值,若属性不存在,先创建再赋值。
hasattr(t, "age")
Out[12]: False
setattr(t, "age", "18")
t.age
Out[14]: '18'
hasattr(t, "age")
Out[15]: True
网友评论