python模块 - functools模块

来源:互联网 发布:防御矩阵异性入侵 编辑:程序博客网 时间:2024/05/09 10:51
http://blog.csdn.net/pipisorry/article/details/26863141

functools模块介绍

functools用于高阶函数:指那些作用于函数或者返回其他函数的函数。通常情况下,只要是可以被当做函数调用的对象就是这个模块的目标。(The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.)

functools.partial函数

partial是针对函数起作用的,并且是部分的,函数中哪些东西可以拆成部分呢?
装饰器是对函数进行包装,算是对函数的整体进行处理(其实是对输入和输出)。
部分的话其实只有对参数进行部分处理了。怎么部分处理的呢?
函数的大致意思就是提前给函数绑定几个参数。
def say(name, age):
    print name, age

func = functools.partial(say, age=5)
func('the5fire')

# 结果是: the5fire 5

场景:有这样的函数:get_useragent(request) 用来获取用户浏览器的ua信息,但是这个函数又不是在主体函数(执行页面渲染的函数)get时调用的,只在模板中的一个filter中调用的(可以理解是在模板渲染时调用的),而filter在执行的时候是不能添加参数的,要怎么处理。
def get(self, request, *args, **kwargs):
    context = {
        'ua_filter': functools.partial(get_useragent, **{"request": request})
    }
    self.render('index.html', context)
/* 对应的大致页面代码如下 */
user-agent: {% ua_filter %}
from:http://blog.csdn.net/pipisorry/article/details/26863141
ref:python中functools宝库下的partial

0 0
原创粉丝点击