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 - n2a = [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" % pagetry: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 + bdef 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 innernew_abc = partial(abc, 2)new_abc(4)
实际上就是给某个函数加上几个固定参数然后返回一个新的函数,对于多个对象更新相同的值来说可以用到。比如:
from functools import partialclass Test(object):def __init__(self):self.name = "lala"self.age = 20def _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-8def 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__printhello2()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
转载于:https://www.cnblogs.com/MnCu8261/p/8763552.html
python中的functools模块相关推荐
- python中functools_python functools模块
functools模块是Python标准模块 1. 模块简介 functools: 用于高阶函数, 指那些作用域函数或者返回其它函数的函数, 通常只要是可以被当做函数调用的对象就是这个模块的目标. 2 ...
- python中functools_Python functools模块完全攻略
functools 模块中主要包含了一些函数装饰器和便捷的功能函数.在 Python 的交互式解释器中先导入 functools 模块,然后输入 [e for e in dir(functools) ...
- 介绍Python中的__future__模块
这篇文章主要介绍了介绍Python中的__future__模块,__future__模块使得在Python2.x的版本下能够兼容更多的Python3.x的特性,需要的朋友可以参考下 Python的每个 ...
- python中的logging记录日志_[ Python入门教程 ] Python中日志记录模块logging使用实例...
python中的logging模块用于记录日志.用户可以根据程序实现需要自定义日志输出位置.日志级别以及日志格式. 将日志内容输出到屏幕 一个最简单的logging模块使用样例,直接打印显示日志内容到 ...
- python使用教程cmd啥意思-Python 中的cmd模块学习
Python中的cmd模块类型提供了一个创建命令行解析器的框架.简单的来说,可以继承Cmd来创建命令行界面,然后对所有想处理的命令command执行do_command方法.默认情况下,它使用read ...
- python中的绘图模块turtle的使用
python中的绘图模块turtle的使用(7-20190125) 文章目录: 还是从一个有趣的小应用开始,turtle的骚操作吧 最近小猪配齐比较流行,下面用turtle绘制一个粉红色的小猪猪吧-- ...
- linux系统python截图不显示中文_Linux运维知识之解决linux系统下python中的matplotlib模块内的pyplot输出图片不能显示中文的问题...
本文主要向大家介绍了Linux运维知识之解决linux系统下python中的matplotlib模块内的pyplot输出图片不能显示中文的问题,通过具体的内容向大家展现,希望对大家学习Linux运维知 ...
- Python中的random模块
Python中的random模块用于随机数生成,对几个random模块中的函数进行简单介绍.如下: random.random() 用于生成一个0到1的随机浮点数.如: import random r ...
- python中的log模块笔记
日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging四大组件记录日志 配置logging的几种方式 向日志输出中添 ...
最新文章
- github报错“remote: Support for password authentication was removed on August 13, 2021. Please use a p”
- 深入浅出python机器学习_9.1.5_通过数据预处理提高模型的准确率_MinMaxScaler
- 如何使用idea快速创建SpringBoot项目
- 旧文重发:程序员的七种武器
- 807. 保持城市天际线
- BUUCTF-Crypto-rabbit+篱笆墙上的影子(栅栏密码)+RSA题解
- 用计算机弹出古诗,电脑屏保不断变化的诗句
- 自己做量化交易软件(22)小白量化之MetaTrader5自动交易1
- 两台电脑的文件共享方式
- Android更改开机画面
- spring-security实现权限管理
- 6.2 不一致数据的转换
- HDOJ 4239 - Decoding EDSAC Data 模拟
- 电脑自动开机win11设置教程
- 小白电脑选购与组装之配置篇
- delegation模式
- Linux系统之复制粘贴命令
- 利用windows上的VMware安装CentOS7(上)
- iOS在image上画文字-画图片
- java游戏应龙女魃转世_华夏上古传说之应龙与女魃的凄美爱情故事