getattr()是python自省的核心函数,其本身的doc介绍如下:

getattr(...)
    getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.

获得对象中一个名为name的属性本身,一般情况下等同于object.name。不同的是
当name属性不存在时,getattr()将返回给定的default值;而直接访问一个不存在的
属性,将会抛出attributeError异常。

1.实现工厂模式

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

import statsout 
def output(data, format="text"):                           
    output_function = getattr(statsout, "output_%s" %format) 
    return output_function(data)

2.注意

getattr返回的是方法本身或是函数的引用,而不是调用
result = obj.method(args)
#func只是函数返回的方法本身
func = getattr(obj, "method")
#这才是调用func方法
result = func(args)

3.特殊处理

Calling both getattr and the method on the same line can make it hard to
handle exceptions properly. To avoid confusing AttributeError exceptions
raised by getattr with similar exceptions raised inside the method, you
can use the following pattern:

try:
    func = getattr(obj, "method")
except AttributeError:
    ... deal with missing method ...
else:
    result = func(args)

The function takes an optional default value, which is used if the attribute
doesn’t exist. The following example only calls the method if it exists:

func = getattr(obj, "method", None)
if func:
    func(args)

Here’s a variation, which checks that the attribute is indeed a callable object before calling it.

func = getattr(obj, "method", None)
if callable(func):
    func(args)
最后由 oucb 编辑于2016年04月11日 22:43