python进阶(4) getattr的用法


问题聚焦:
熟悉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

    <喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHByZSBjbGFzcz0="brush:java;">result = obj.method(args) // 使用getattr func = getattr(obj, "method") result = func(args) // 或者写成一行 result = getattr(obj, "method")(args)


    异常安全的写法:

    主要有两种异常

    AttributeError: 对象中没有该属性

    try:
        func = getattr(obj, "method")
    except AttributeError:
        ...... deal
    else:
        result = func(args)
    
    // 或指定默认返回值
    func = getattr(obj, "method", None)
    if func:
        func(args)
    
    

    TypeError: 不可调用

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

    用getattr实现工厂方法:

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

    import statsout 
    def output(data, format="text"):                           
        output_function = getattr(statsout, "output_%s" %format) 
        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文档

评论关闭