python中的functools模块
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模块的更多相关文章
- Python中的random模块,来自于Capricorn的实验室
Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...
- Python中的logging模块
http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...
- Python中的random模块
Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...
- 浅析Python中的struct模块
最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概了解了,在这里做一下简单的总结. 了解c语言 ...
- python中的StringIO模块
python中的StringIO模块 标签:python StringIO 此模块主要用于在内存缓冲区中读写数据.模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分 ...
- python中的select模块
介绍: Python中的select模块专注于I/O多路复用,提供了select poll epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kqu ...
- Python中的re模块--正则表达式
Python中的re模块--正则表达式 使用match从字符串开头匹配 以匹配国内手机号为例,通常手机号为11位,以1开头.大概是这样13509094747,(这个号码是我随便写的,请不要拨打),我们 ...
- python中的shutil模块
目录 python中的shutil模块 目录和文件操作 归档操作 python中的shutil模块 shutil模块对文件和文件集合提供了许多高级操作,特别是提供了支持文件复制和删除的函数. 目录和文 ...
- Python中使用operator模块实现对象的多级排序
Python中使用operator模块实现对象的多级排序 今天碰到一个小的排序问题,需要按嵌套对象的多个属性来排序,于是发现了Python里的operator模块和sorted函数组合可以实现这个功能 ...
随机推荐
- mpvue两小时,产出一个《点钞辅助工具》小程序
CoffeeScript,Pug,Sass使用 以下内容门槛较高,如看不懂或觉得需要继续了解,结尾处放置了原视频流程与GitHub地址,欢迎琢磨与Star,谢谢. 文章不做技术语法解读,如不清楚,请前 ...
- TDD 与 CI 在 Python 中的实践
社区化产品的长久生存之道可能莫过于对迭代周期的控制.还记得以前采用老土的阶段开发的年代,将软件生命周期分为各个阶段,当到达每个阶段的里程碑则集中所有的资源.人力作全面冲刺.每次到了里程碑的检查点冲过了 ...
- 【分享】Java学习之路:不走弯路,就是捷径
1.如何学习程序设计? JAVA是一种平台,也是一种程序设计语言,如何学好程序设计不仅仅适用于JAVA,对C++等其他程序设计语言也一样管用.有编程高手认为,JAVA也好C也好没什么分别,拿来就用.为 ...
- Linux环境下使用n更新node版本失败的原因与解决
Linux环境为CentOS 6.5 64位,阿里云低配服务器...学生优惠,然而下个月即将过期,真是个悲伤的故事 很久之前就安装了node,但是一直没有进行过升级,近日因为将部分异步代码更新为采用原 ...
- 微信小程序选择并上传图片
上传图片 API: wx.chooseImage() 和 wx.uploadFile() wx.chooseImage({ count: 1, // 默认9 sizeType: ['origina ...
- github添加ssh连接用户
最近打算用flask写一个自己的博客网站,打算把代码放在GitHub上,使用ssh访问.记录下GitHub配置ssh用户的流程. 1.在本地电脑或云服务器上生成ssh公钥和私钥,window下可以进入 ...
- 博客目录 Blog directory
Linux 学习笔记 Linux/Mac 挂载远程服务器目录到本地 --Mount remote server directory to local PC 远程连接服务器端Jupyter Notebo ...
- PAT甲题题解-1061. Dating (20)-字符串处理,水水
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h&g ...
- BackBone及其实例探究
摘要 我们小组对MVC框架进行了学习.我的队友们已经在博客中对MVC的设计模式及优缺点进行了详细的探讨与分析,因此我的博客中只对MVC进行简单的介绍,而我将把重心放在Backbone MVC框架一 ...
- 【MOOC EXP】Linux内核分析实验四报告
程涵 原创博客 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 [使用库函数API和C代码中嵌入汇编代 ...