getattr()函数是Python自省的核心函数,具体使用大体如下:

获取对象引用getattr
Getattr用于返回一个对象属性,或者方法

  1. class A:
  2. def __init__(self):
  3. self.name = 'zhangjing'
  4.     #self.age='24'
  5. def method(self):
  6. print"method print"
  7. Instance = A()
  8. print getattr(Instance , 'name, 'not find') #如果Instance 对象中有属性name则打印self.name的值,否则打印'not find'
  9. print getattr(Instance , 'age', 'not find')   #如果Instance 对象中有属性age则打印self.age的值,否则打印'not find'
  10. print getattr(a, 'method', 'default')
  11. #如果有方法method,否则打印其地址,否则打印default
  12. print getattr(a, 'method', 'default')()
  13. #如果有方法method,运行函数并打印None否则打印default

注:使用getattr可以轻松实现工厂模式。 
例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

    1. import statsout
    2. def output(data, format="text"):
    3. output_function = getattr(statsout, "output_%s" % format)
    4. return output_function(data)
setattr( object, name, value)

This is the counterpart of getattr(). The arguments
are an object, a string and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the attribute,
provided the object allows it. For example, setattr(x,
'foobar', 123)
 is equivalent to
x.foobar = 123.

这是相对应的getattr()。参数是一个对象,一个字符串和一个任意值。字符串可能会列出一个现有的属性或一个新的属性。这个函数将值赋给属性的。该对象允许它提供。例如,setattr(x,“foobar”,123)相当于x.foobar = 123。

delattr(       object, name)

This is a relative of setattr(). The arguments are
an object and a string. The string must be the name of one of the object’s
attributes. The function deletes the named attribute, provided the object allows
it. For example, delattr(x, 'foobar') is
equivalent to del x.foobar.

与setattr()相关的一组函数。参数是由一个对象(记住python中一切皆是对象)和一个字符串组成的。string参数必须是对象属性名之一。该函数删除该obj的一个由string指定的属性。delattr(x, 'foobar')=del x.foobar

  • hasattr用于确定一个对象是否具有某个属性。

    语法:
    hasattr(object, name) -> bool
    判断object中是否有name属性,返回一个布尔值。

>>> li=["zhangjing","zhangwei"]

>>> getattr(li,"pop")
<built-in method pop of list object at 0x011DF6C0>
>>> li.pop
<built-in method pop of list object at 0x011DF6C0>

>>> li.pop()
'zhangwei'

>>> getattr(li,"pop")()
'zhangjing'

>>>getattr(li, "append")("Moe") 

[转]Python的getattr(),setattr(),delattr(),hasattr()的更多相关文章

  1. Python的getattr(),setattr(),delattr(),hasattr()及类内建__getattr__应用

    @Python的getattr(),setattr(),delattr(),hasattr() 先转一篇博文,参考.最后再给出一个例子 getattr()函数是Python自省的核心函数,具体使用大体 ...

  2. Python的getattr(),setattr(),delattr(),hasattr()

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

  3. python 内置函数的补充 isinstance,issubclass, hasattr ,getattr, setattr, delattr,str,del 用法,以及元类

    isinstance   是 python中的内置函数 , isinstance()用来判断一个函数是不是一个类型 issubclass  是python 中的内置函数,  用来一个类A是不是另外一个 ...

  4. isinstance/type/issubclass的用法,反射(hasattr,getattr,setattr,delattr)

    6.23 自我总结 面向对象的高阶 1.isinstance/type/issubclass 1.type 显示对象的类,但是不会显示他的父类 2.isinstance 会显示的对象的类,也会去找对象 ...

  5. Python hasattr,getattr,setattr,delattr

    #!/usr/bin/env python # -*- coding:utf-8 -*- # 作者:Presley # 邮箱:1209989516@qq.com # 时间:2018-11-04 # 反 ...

  6. python动态函数hasattr,getattr,setattr,delattr

    hasattr(object,name) hasattr用来判断对象中是否有name属性或者name方法,如果有,染回true,否则返回false class attr():     def fun( ...

  7. python反射hasattr getattr setattr delattr

    反射 : 是用字符串类型的名字 去操作 变量 相比于用eval('print(name)') 留有 安全隐患 反射 就没有安全问题 hasattr 语法: hasattr(object, name)o ...

  8. hasattr getattr setattr delattr --> (反射)

    class Room: def __init__(self,name): self.name = name def big_room(self): print('bigroot') R = Room( ...

  9. Python笔记_第四篇_高阶编程_反射_(getattr,setattr,deattr,hasattr)

    1. 元数据和反射概念: 有关程序及其类型的数据成为元数据(metadata),他保存在程序的程序集中. 反射这个词儿听起来比较陌生.程序在运行时,可以查看其它程序集或其本身的元数据.一个运行的程序查 ...

随机推荐

  1. Windows Phone WebClient的使用

    webClient对象可用来下载XML文件,程序集等这些数据,其可以实现按需下载,所以还是有必要了解的.其主要包含几个事件:                                       ...

  2. 310实验室(六)CMake学习心得

    树形结构方式布局. OTL 中每一个文件中的CMakeLists.txt 有不同的作用:按查看文件的先后顺便进行分层理解, 根文件即第一次 中的.txt是 启用 CMAKE_MODULE_PATH模板 ...

  3. postgresql----排序ORDER BY,分组GROUP BY,分页OFFSET&&LIMIT

    一.GROUP BY 使用GROUP BY分组查询在SELECT子句中只能出现分组字段和聚合函数,HAVING子句相当于WHERE,使用条件过滤数据. 示例1.以a,b分组查询tbl_insert表, ...

  4. 170628、springboot编程之Druid数据源和监控配置一

    Spring Boot默认的数据源是:org.apache.tomcat.jdbc.pool.DataSource,那么如何修改数据源呢?我已目前使用比较多的阿里数据源Druid为例,如果使用其他的数 ...

  5. Oracle之rman命令的使用全备输出信息的详解(51CTO风哥rman课程)

    rman连接数据库 rman target/ catalog rman/rman123456 运行全备命令 backup database; 查看备份集 list backupset;

  6. angular $http服务详解

    它是对原生XMLHttpRequest对象的简单封装, 这个方法会返回一个promise对象,具有sccess和error两个方法. 当然,我们也可以在响应返回时用then 方法来处理,会得到一个特殊 ...

  7. 升级mac xcode打包证书报错 git 报错

    reset tryAgain git 在钥匙串中找不到指定的项  重新配置公钥撕咬 SSH keys An SSH key allows you to establish a secure conne ...

  8. django的restfulapi

    Django Rest framework 的流程大概是这样的 建立 Models 依靠 Serialiers 将数据库取出的数据 Parse 为 API 的数据(可用于返回给客户端,也可用于浏览器显 ...

  9. andorid ListView和GirdView 与ScrollView 冲突

    1.listview解决方法 public static void setListViewHeightBasedOnChildren(ListView listView) { if(listView ...

  10. Django Rest Framework(2)-----序列化详解(serializers)

    REST framework中的序列化类与Django的Form和ModelForm类非常相似.我们提供了一个Serializer类,它提供了一种强大的通用方法来控制响应的输出,以及一个ModelSe ...