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

 

感谢作者 ---> 原文链接

hasattr(object, name)

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

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> hasattr(t, "name") #判断对象有name属性
8 True
9 >>> hasattr(t, "run") #判断对象有run方法
10 True
11 >>>

getattr(object, name[,default])

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

1 >>> class test():
2 ...     name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "name") #获取name属性,存在就打印出来。
8 'xiaohua'
9 >>> getattr(t, "run") #获取run方法,存在就打印出方法的内存地址。
10 <bound method test.run of <__main__.test instance at 0x0269C878>>
11 >>> getattr(t, "run")() #获取run方法,后面加括号可以将这个方法运行。
12 'HelloWord'
13 >>> getattr(t, "age") #获取一个不存在的属性。
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 AttributeError: test instance has no attribute 'age'
17 >>> getattr(t, "age","18") #若属性不存在,返回一个默认值。
18 '18'
19 >>>

setattr(object, name, values)

给对象的属性赋值,若属性不存在,先创建再赋值。

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> hasattr(t, "age") #判断属性是否存在
8 False
9 >>> setattr(t, "age", "18") #为属相赋值,并没有返回值
10 >>> hasattr(t, "age") #属性存在了
11 True
12 >>>

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

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "age") #age属性不存在
8 Traceback (most recent call last):
9 File "<stdin>", line 1, in <module>
10 AttributeError: test instance has no attribute 'age'
11 >>> getattr(t, "age", setattr(t, "age", "18")) #age属性不存在时,设置该属性
12 '18'
13 >>> getattr(t, "age") #可检测设置成功
14 '18'
15 >>>

请使用手机"扫一扫"x

最新文章

  1. event
  2. Linux Ubuntu12.04下安装OpenCv2.4.10
  3. 使用Gitosis搭建Git服务器
  4. c++11新特性(了解)
  5. freemarker中修改和添加功能中包含checkbox复选框默认选中需求的解决方式
  6. 7.3.2 Using Backups for Recovery 使用备份用于恢复
  7. 使用nice命令调整进程优先级
  8. hdfs经常使用命令
  9. Android 应用程序窗口显示状态操作(requestWindowFeature()的应用)
  10. C# delegate event func action 匿名方法 lambda表达式
  11. Android轮播图
  12. (十一)Updating Documents
  13. 【Code Tools】Java微基准测试工具JMH之中级篇
  14. 【BZOJ2749】【HAOI2012】外星人[欧拉函数]
  15. Sqoop异常:Please set $ACCUMULO_HOME to the root of your Accumulo installation.
  16. 设计模式_享元设计模式(flyweight)
  17. linux elasticsearch-5.1.1的安装
  18. JVM 系列(一)类加载
  19. 编译后class$1,class$2,class$innerclass中的$的含义
  20. 用python的turtle画图

热门文章

  1. 服务器返回的14种常见HTTP状态码
  2. svg的基本图形与属性【小尾巴的svg学习笔记1】
  3. Jquery插件之ajaxForm简介
  4. Git的使用(详细)
  5. sql:表中数据全部删除之后,重新插入时,从1开始增加
  6. 详细讲解:通过composer安装TP5.1(Thinkphp5.1)
  7. 【转】android布局--Android fill_parent、wrap_content和match_parent的区别
  8. python第一章练习题
  9. HTML页面生成ASPX页面
  10. machine learning trends from nips14