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. HDU 4455 Substrings[多重dp]

    Substrings Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  2. 服务器报错 500,请确保 ASP.NET State Service(ASP.NET 状态服务)已启动

    报错信息: 解决方案: 开启此服务

  3. 无法远程访问Mysql

    1.故障状态 [root@server02 ~]# mysql -utuser -h192. -p Enter password: ERROR (HY000): Can't connect to My ...

  4. 170705、springboot编程之自定义properties

    spring boot使用application.properties默认了很多配置.但需要自己添加一些配置的时候,可以这样用,如下! 在application.properties文件中增加信息 1 ...

  5. yii2.0 如何按需加载并管理CSS样式及JS脚本

    链接:http://www.yiichina.com/tutorial/399 (注:以下为Yii2.0高级应用测试) Yii2.0对于CSS/JS 管理,使用AssetBundle资源包类. 视图如 ...

  6. JS生成GUID方法

    function GUID() { this.date = new Date(); /* 判断是否初始化过,如果初始化过以下代码,则以下代码将不再执行,实际中只执行一次 */ if (typeof t ...

  7. CodeForces Roads not only in Berland(并查集)

    H - Roads not only in Berland Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d ...

  8. A Benchmark Comparsion of Monocular Visual-Inertial Odometry Algorithms for Flying Robots论文笔记

    摘要: 本文主要比较单目VIO的算法在飞行机器人上运行的性能,测试使用统一数据集为EuRoC.其中评价指标为:姿态估计精度.每帧处理时间以及CPU和内存负载使用率,同时还有RMSE(运行轨迹与真实轨迹 ...

  9. Java中参数传递时值传递的机制分析

    参数传递是什么?      在C的函数或是JAVA的方法中,向一个函数或方法内部传递一个参数,比如:   void fun( int num ){     num+=2 ; }   int a = 3 ...

  10. 把大象装进冰箱的N种方法

    作者:折剑头链接:https://www.zhihu.com/question/49214119/answer/115728034来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...