python 的getattr的用法

转载:http://blog.csdn.net/zs634134578/article/category/1282486


问题聚焦:
熟悉getattr的应该知道,getattr(a, 'b')的作用就和a.b是一样的
那么这个内建函数有什么作用呢,最方便的无疑是使用它来实现工厂方法(Factory Method)模式
另外,在回调函数里也经常使用这个函数,对回调理解不深,这里不再举例

先看一下 官方文档

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, defaultis returned if provided, otherwise AttributeError is raised.

参数说明:

  • object:对象的实例
  • name:字符串,对象的成员函数的名字或者成员变量
  • default:当对象中没有该属性时,返回的默认值
  • 异常:当没有该属性并且没有默认的返回值时,抛出"AttrbuteError"

作用:

getattr(object, name)  =  object.name

Demo

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. result = obj.method(args)  
  2.   
  3. // 使用getattr  
  4. func = getattr(obj, "method")  
  5. result = func(args)  
  6. // 或者写成一行  
  7. result = getattr(obj, "method")(args)  


异常安全的写法:

主要有两种异常

AttributeError: 对象中没有该属性

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. try:  
  2.     func = getattr(obj, "method")  
  3. except AttributeError:  
  4.     ...... deal  
  5. else:  
  6.     result = func(args)  
  7.   
  8. // 或指定默认返回值  
  9. func = getattr(obj, "method"None)  
  10. if func:  
  11.     func(args)  

TypeError: 不可调用

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. func = getattr(obj, "method"None)  
  2. if callable(func):  
  3.     func(args)  

用getattr实现工厂方法:

Demo:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import statsout   
  2. def output(data, format="text"):                             
  3.     output_function = getattr(statsout, "output_%s" %format)   
  4.     return output_function(data)  

这个例子中可以根据传入output函数的format参数的不同 去调用statsout模块不同的方法(用格式化字符串实现output_%s)


参考资料:

http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html Python找那个的getattr()函数详解

http://docs.python.org/2.7/library/functions.html?highlight=getattr#getattr  python2.7文档


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值