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. ucos获得系统时间OSTimeGet();

    OSTimeGet() 获得系统节拍值OSTime,滴答定时器中断一次OSTime++.

  2. VS相关

    快速显示函数名称 ctrl+alt+T 显示函数参数说明 ctrl+shift+space,光标放在函数里面 link 1123错误,vs2010的问题. 点击工程-属性-ManifestTool-I ...

  3. JAVA eclipse Maven项目红叹号解决方案

    我是通过 Windows --> show view --> problems 查看到发现 ch.qos.logback 1.1.1 出现了错误, 于是我换成了 ch.qos.logbac ...

  4. [UOJ#461]新年的Dog划分[二分图染色、二分]

    题意 给你一张无向连通图,你并不知道有哪些边,你首先要回答这张图是否是二分图,如果是,回答这张图黑白染色过后的任意一个点集.你需要在2000次询问内找到结果,每次你可以询问原图中一个边集删掉后是否还连 ...

  5. C# Language Specification 5.0 (翻译)第四章 类型

    C# 语言的类型分为两大类:值类型(value type)和引用类型(reference type),而它们又都同时具有至少一个类型形参的泛型类型(generic type).类型形参(type pa ...

  6. sudo apt-get update 去除设置的代理

    今天想装个软件(wine),使用 sudo apt-get update 命令时,发现给出很多Ign 语句,总出现 Connecting to proxy.http://10.0.126.1:1312 ...

  7. mui框架(二)

    1.底部导航切换界面 HTML部分: <nav class="mui-bar mui-bar-tab"> <a id="defaultTab" ...

  8. mysql学习(2)-Navicat Premium 12 链接MySQL8.0.11数据库报2059错误

    Navicat Premium 12 链接MySQL8.0.11数据库报2059错误 1,问题现象 安装完MySQL8.0.11和Navicat Premium12后,我们会用Navicat去测试连接 ...

  9. Matlab批量处理指定文件夹下的所有音频文件

    filedir='E:/source/Wavfile/*.wav'; % 设置路径 outfiledir='E:/output/Wavfile/'; infiledir='E:/source/Wavf ...

  10. 使用Samba服务程序,让linux系统之间共享文件

    yum  install -y   cifs-utils mkdir  /database    创建挂载目录 在root家目录创建认证文件(依次为SMB用户名.SMB用户密码.SMB共享域)   v ...