functools模块可以作用于所有的可以被调用的对象,包括函数 定义了__call__方法的类等

  1 functools.cmp_to_key(func)

    将比较函数(接受两个参数,通过比较两个参数的大小返回负值,0,或者正数)转换为key function(返回一个值用来比较或者排序的可调用对象),

    例如: sorted(iterable, functools.cmp_to_key(locale.strcoll))

def cmp1(n1, n2):
return n1 - n2 a = [1, 6, 2, 9]
print(sorted(a, key=functools.cmp_to_key(cmp1)))

  2 @functools.lru_cache(maxsize=128, typed=False)

    首先这是一个装饰器

    其次,介绍一下LRU算法:

      LRU是最常用的缓存算法,全称叫“Least Recently Used”,顾名思义,就是在缓存miss 并且缓存空间已满的时候,将最久没访问过的数据删除从而腾出空间。

    然后,说一下这个装饰器的两个参数的含义:

      maxsize: 表示缓存大小,如果设置为None,表示不限制,设置为0表示不启用缓存机制

      typed:如果设置为True,则该装饰器所装饰的函数的参数即使值相等(比如说 3 == 3.0 ),但类型不同(一个是整型一个是浮点),也会被区分对待为不同的缓存

    然后,说明一下这个装饰器对所装饰的函数的要求,

      1 函数的参数接收的值必须是不可变对象,像字符串,数字,元组等都属于此列 

      2 其次函数返回的对象最好也是不可变对象,当然这一点没有硬性要求,但是道理大家懂。

    来一个栗子:

@functools.lru_cache(2526)
def get_resource(page): url = "https://urls_does_not_contain_pornographic_informations/%s" % page try:
with urllib.request.urlopen(url) as s:
return s.read()
except urllib.error.HTTPError:
return 'Not Found' for i in range(1, 2526):
pep = get_resource(i)
print(pep)

  3 @functools.total_ordering

    首先这是一个类装饰器,这个类装饰器要求它所定义的类中必须定义:

      1  小于__lt__(), 小于等于__le__(),大于__gt__(),大于等于__ge__()中的一个

      2  还要定义等于__eq__()方法。

    只要我们按照要求定义了这些方法,该装饰器就会为我们完成其余的比较排序方法 。

  4 functools.partial(func, *args, **keywords)

     类似于这样:

def abc(a, b):
print a + b def partial(func, *args, **kwargs):
args_li = list(args) def inner(*nargs, **nkwargs):
args_li.extend(nargs)
kwargs.update(nkwargs)
return func(*args_li, **kwargs) return inner new_abc = partial(abc, 2) new_abc(4)

实际上就是给某个函数加上几个固定参数然后返回一个新的函数,对于多个对象更新相同的值来说可以用到。比如:

from functools import partial

class Test(object):
def __init__(self):
self.name = "lala"
self.age = 20 def _update_attr(obj, update_dic):
map(lambda item: setattr(obj, item[0], item[1]), update_dic.iteritems()) update_attr = partial(_update_attr, update_dic={"name": "mncu", "age": 18}) test_obj_list = [Test() for i in xrange(20)] map(update_attr, test_obj_list) for test_obj in test_obj_list:
print test_obj.name, test_obj.age

  5 class functools.partialmethod(func, *args, **keywords)

    作用类似于上面的partial函数,但这个方法作用于类的方法,返回的是方法而不是函数。

>>> class Cell(object):
... def __init__(self):
... self._alive = False
... @property
... def alive(self):
... return self._alive
... def set_state(self, state):
... self._alive = bool(state)
... set_alive = partialmethod(set_state, True)
... set_dead = partialmethod(set_state, False)
...
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True

  6 functool.update_wrapper(wrapper, wrapped[, assigned][, updated])

      functools.wraps(wrapped[, assigned][, updated])

    在python中,当一个函数被装饰器装饰后,这个函数名字对应的函数对象实际上是那个装饰器函数,也就是该函数名对应的的__name__以及__doc__实际上已经改变了,这就导致很难调试。而update_wrapper以及wraps就是用来解决这个问题。

#!/usr/bin/env python
# encoding: utf-8 def wrap(func):
def call_it(*args, **kwargs):
"""wrap func: call_it"""
print 'before call'
return func(*args, **kwargs)
return call_it @wrap
def hello():
"""say hello"""
print 'hello world' from functools import update_wrapper
def wrap2(func):
def call_it(*args, **kwargs):
"""wrap func: call_it2"""
print 'before call'
return func(*args, **kwargs)
return update_wrapper(call_it, func) @wrap2
def hello2():
"""test hello"""
print 'hello world2' if __name__ == '__main__':
hello()
print hello.__name__
print hello.__doc__ print
hello2()
print hello2.__name__
print hello2.__doc__

结果:

  before call
  hello world
  call_it
  wrap func: call_it

  before call
  hello world2
  hello2
  test hello

from functools import wraps
def wrap3(func):
@wraps(func)
def call_it(*args, **kwargs):
"""wrap func: call_it2"""
print 'before call'
return func(*args, **kwargs)
return call_it @wrap3
def hello3():
"""test hello 3"""
print 'hello world3'

结果:

  before call
  hello world3
  hello3
  test hello 3

参考:

  https://blog.theerrorlog.com/simple-lru-cache-in-python-3.html, 作者: Kay Zheng

  http://www.wklken.me/posts/2013/08/18/python-extra-functools.html  作者:WKLKEN

python中的functools模块的更多相关文章

  1. Python中的random模块,来自于Capricorn的实验室

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  2. Python中的logging模块

    http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...

  3. Python中的random模块

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  4. 浅析Python中的struct模块

    最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概了解了,在这里做一下简单的总结. 了解c语言 ...

  5. python中的StringIO模块

    python中的StringIO模块 标签:python StringIO 此模块主要用于在内存缓冲区中读写数据.模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分 ...

  6. python中的select模块

    介绍: Python中的select模块专注于I/O多路复用,提供了select  poll  epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kqu ...

  7. Python中的re模块--正则表达式

    Python中的re模块--正则表达式 使用match从字符串开头匹配 以匹配国内手机号为例,通常手机号为11位,以1开头.大概是这样13509094747,(这个号码是我随便写的,请不要拨打),我们 ...

  8. python中的shutil模块

    目录 python中的shutil模块 目录和文件操作 归档操作 python中的shutil模块 shutil模块对文件和文件集合提供了许多高级操作,特别是提供了支持文件复制和删除的函数. 目录和文 ...

  9. Python中使用operator模块实现对象的多级排序

    Python中使用operator模块实现对象的多级排序 今天碰到一个小的排序问题,需要按嵌套对象的多个属性来排序,于是发现了Python里的operator模块和sorted函数组合可以实现这个功能 ...

随机推荐

  1. python3 的 round 函数的 练习

    python3 的 round 函数感觉很别扭,其运算结果与习惯不相符.特记录下来: 代码 ''' python 3的 round 函数 是"四舍六入五成双"的 https://w ...

  2. VS 远程调试 Azure Web App

    如果能够远程调试部署在 Azure 上的 Web App,将会极大的提高我们修复 bug 的效率.Visual Studio 一贯以功能强大.好用著称,当然可以通吃基于 Azure 应用的创建.发布和 ...

  3. 用 IIS 搭建 mercurial server

    mercurial server 对于代码管理工具,更多的人可能对 Git 更熟悉一些(Git太火了).其实另外一款分布式代码管理工具也被广泛的使用,它就是 mercurial.当多人协作时最好能够通 ...

  4. OpenGL学习(2)——绘制三角形(补)

    对上一篇的补充,通过绘制三角形来完成矩形的绘制.此外,完成章节后练习. 绘制矩形 一个矩形由两个三角形组成,因此绘制矩形需要绘制两个三角形,一共6个顶点,其中2个顶点重复画了两次. 为了减小开销,仅储 ...

  5. GitHubDesktop权限问题解决办法

    Desktop对于管理仓库非常方便.实用 很多人实用Desktop将仓库项目clone到本地 但是更新后同步时出现了如下权限错误: Error Authentication failed. You m ...

  6. kali linux 安装Nessus

    Nessus 介绍: Nessus 是目前全世界最多人使用的系统漏洞扫描与分析软件.总共有超过75,000个机构使用Nessus 作为扫描该机构电脑系统的软件. 下载Nessus,我的是64为,我选择 ...

  7. 第十七次ScrumMeeting博客

    第十七次ScrumMeeting博客 本次会议于12月7日(四)22时整在3公寓725房间召开,持续20分钟. 与会人员:刘畅.辛德泰.张安澜.赵奕.方科栋. 1. 每个人的工作(有Issue的内容和 ...

  8. http和https的加密方式

    BS盛行的今天有点网络只是很必要啊,首先需要个网络抓包工具wireshark, http:http通过三次握手来通信,握手过程看图1 https:https = http + ssl(secure s ...

  9. Linux shell(1)

    Linux的Shell种类众多,常见的有:Bourne Shell(/usr/bin/sh或/bin/sh).Bourne Again Shell(/bin/bash).C Shell(/usr/bi ...

  10. Beta阶段冲刺-1

    1. 新成员 新加入成员,克克飞同学,任务是去弄公众号相关的部分. 队员 个人简介 博客地址 杨晨露 每天都在开会的PM http://www.cnblogs.com/ycll/ 游舒婷 每天都在装死 ...