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. 心脏滴血HeartBleed漏洞研究及其POC

    一.漏洞原理: 首先声明,我虽然能看懂C和C++的每一行代码,但是他们连在一起我就不知道什么鬼东西了.所以关于代码说理的部分只能参考其他大牛的博客了. /* 据说源码中有下面两条语句,反正我也没看过源 ...

  2. iOS 8 新特性介绍

    来源:nshipster.cn 发布时间:2014-07-06 阅读次数:2152 随便去问任何人,他们都会告诉你WWDC2014是近年来最为激动的回忆. 整个大会没有发布任何新硬件,它是一次史无前例 ...

  3. Malformed \uxxxx encoding

    今天碰到个问题. FATAL [btir.server.ServerStartup:54] - <java.lang.IllegalArgumentException: Malformed \u ...

  4. 系统事件管理(Events) ---- HTML5+

    模块:events Events模块管理客户端事件,包括系统事件,如扩展API加载完毕.程序前后台切换等. 比如说:网络的链接的和断开这种事件,系统从前台走到后台这种事件: 不包括:点击和滑动页面事件 ...

  5. Linux系统下 Supervisor 安装搭建

    在 web 应用部署到线上后,需要保证应用一直处于运行状态,在遇到程序异常.报错等情况,导致 web 应用终止时,需要保证程序可以立刻重启,继续提供服务. 所以,就需要一个工具,时刻监控 web 应用 ...

  6. 修改js confirm alert 提示框文字

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  7. [Gradle] 输出构建 APK 的版本名到文件

    android { // 输出版本名到 build 目录下的 version_name.txt 文件 applicationVariants.all { variant -> project.t ...

  8. 用angular中的ng-repeat和ng-show来实现tab选项卡

    虽然我们可以用angular中的路由来做tab选项卡,但是那会让我们建立很多的页面来引入,或者建立 <script type="text/ng-template" id=&q ...

  9. .NET获取Html字符串中指定标签的指定属性的值

    using System.Text; using System.Text.RegularExpressions; //以上为要用到的命名空间 /// <summary> /// 获取Htm ...

  10. python的tqdm模块

    Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator). 根据要求安装依赖即可. 可以很方便的在 ...