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. PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法

    PHP 的异常处理.错误的抛出及回调函数等面向对象的错误处理方法: http://www.jb51.net/article/32498.htm http://www.cnblogs.com/hongf ...

  2. 学习POC框架pocsuite--编写hellowordPOC

    在这里,首先向安全圈最大的娱乐公司,某404致敬. 参考博文 https://www.seebug.org/help/dev 向seebug平台及该文原作者致敬,虽然并不知道是谁 长话短说其实,可自由 ...

  3. python的内存管理与垃圾回收机制学习

    一.python内存申请: 1.python的内存管理分为六层:最底的两层有OS控制.第三层是调用C的malloc和free等进行内存控制.第四层第五层是python的内存池.最上层使我们接触的直接对 ...

  4. 三、微信小游戏开发 --- 小游戏API调用Platform

    微信小游戏API Platform主要是Egret用于来调用平台的SDK的. 在Egret中使用接口定义Platform. Egret项目中默认的platform值是DebugPlatform. 发布 ...

  5. Express框架(http服务器 + 路由)

    index.js 使用express框架搭建http服务器,和实现路由功能. var express = require('express'); var app = express(); // 主页输 ...

  6. [转帖]双剑合璧:CPU+GPU异构计算完全解析

    引用自:http://tech.sina.com.cn/mobile/n/2011-06-20/18371792199.shtml 这篇文章写的深入浅出,把异构计算的思想和行业趋势描述的非常清楚,难得 ...

  7. Android自定义控件实战——仿淘宝商品浏览界面

    转载请声明出处http://blog.csdn.net/zhongkejingwang/article/details/38656929 用手机淘宝浏览商品详情时,商品图片是放在后面的,在第一个Scr ...

  8. ubuntu下安装meshlab

    PPA 安装,打开终端,输入以下命令: sudo add-apt-repository ppa:zarquon42/meshlab sudo apt-get update sudo apt-get i ...

  9. python threading.thread

    Thread 是threading模块中最重要的类之一,可以使用它来创建线程.有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法:另一种是创建一个threading.Thread对 ...

  10. Python开发【前端】:Ajax(二)

    原生Ajax.JQuery.伪Ajax三种方式使用优先级 如果发送的是[普通数据] jQuery XMLHttpRequest iframe 如果发送的是[文件] iframe jQuery(Form ...