functools模块是Python的标准库的一部分,它是为高阶函数而实现的。高阶函数是作用于或返回另一个函数或多个函数的函数。一般来说,对这个模块而言,任何可调用的对象都可以作为一个函数来处理。

functools 提供了 11个函数:

1. cached_property

将类的方法转换为一个属性,该属性的值计算一次,然后在实例的生命周期中将其缓存作为普通属性。与 property() 类似,但添加了缓存,对于在其他情况下实际不可变的高计算资源消耗的实例特征属性来说该函数非常有用。

# cached_property 缓存属性
class cached_property(object):"""Decorator that converts a method with a single self argument into aproperty cached on the instance.Optional ``name`` argument allows you to make cached properties of othermethods. (e.g.  url = cached_property(get_absolute_url, name='url') )"""def __init__(self, func, name=None):# print(f'f: {id(func)}')self.func = funcself.__doc__ = getattr(func, '__doc__')self.name = name or func.__name__def __get__(self, instance, type=None):# print(f'self func: {id(self.func)}')# print(f'instance: {id(instance)}')if instance is None:return selfres = instance.__dict__[self.name] = self.func(instance)return resclass F00():@cached_propertydef test(self):# cached_property 将会把每个实例的属性存储到实例的__dict__中, 实例获取属性时, 将会优先从__dict__中获取,则不会再次调用方法内部的过程print(f'运行test方法内部过程')return 3@propertydef t(self):print('运行t方法内部过程')return 44f = F00()
print(f.test)  # 第一次将会调用test方法内部过程
print(f.test)  # 再次调用将直接从实例中的__dict__中直接获取,不会再次调用方法内部过程
print(f.t)     # 调用方法内部过程取值
print(f.t)     # 调用方法内部过程取值# 结果输出
# 运行test方法内部过程
# 3
# 3
# 运行t方法内部过程
# 44
# 运行t方法内部过程
# 44

2. cmp_to_key

在 list.sort 和 内建函数 sorted 中都有一个 key 参数

x = ['hello','worl','ni']
x.sort(key=len)
print(x)
# ['ni', 'worl', 'hello']

3. lru_cache

允许我们将一个函数的返回值快速地缓存或取消缓存。
该装饰器用于缓存函数的调用结果,对于需要多次调用的函数,而且每次调用参数都相同,则可以用该装饰器缓存调用结果,从而加快程序运行。
该装饰器会将不同的调用结果缓存在内存中,因此需要注意内存占用问题。

from functools import lru_cache
@lru_cache(maxsize=30)  # maxsize参数告诉lru_cache缓存最近多少个返回值
def fib(n):if n < 2:return nreturn fib(n-1) + fib(n-2)
print([fib(n) for n in range(10)])
fib.cache_clear()   # 清空缓存

4. partial

用于创建一个偏函数,将默认参数包装一个可调用对象,返回结果也是可调用对象。
偏函数可以固定住原函数的部分参数,从而在调用时更简单。

from functools import partialint2 = partial(int, base=8)
print(int2('123'))
# 83

5. partialmethod

对于python 偏函数partial理解运用起来比较简单,就是对原函数某些参数设置默认值,生成一个新函数。而如果对于类方法,因为第一个参数是 self,使用 partial 就会报错了。

class functools.partialmethod(func, /, *args, **keywords) 返回一个新的 partialmethod 描述器,其行为类似 partial 但它被设计用作方法定义而非直接用作可调用对象。

func 必须是一个 descriptor 或可调用对象(同属两者的对象例如普通函数会被当作描述器来处理)。

当 func 是一个描述器(例如普通 Python 函数, classmethod(), staticmethod(), abstractmethod() 或其他 partialmethod 的实例)时, 对 __get__ 的调用会被委托给底层的描述器,并会返回一个适当的 部分对象 作为结果。

当 func 是一个非描述器类可调用对象时,则会动态创建一个适当的绑定方法。 当用作方法时其行为类似普通 Python 函数:将会插入 self 参数作为第一个位置参数,其位置甚至会处于提供给 partialmethod 构造器的 args 和 keywords 之前。

from functools import partialmethodclass Cell:def __init__(self):self._alive = False@propertydef alive(self):return self._alivedef set_state(self, state):self._alive = bool(state)set_alive = partialmethod(set_state, True)set_dead = partialmethod(set_state, False)print(type(partialmethod(set_state, False)))# <class 'functools.partialmethod'>c = Cell()
c.alive
# Falsec.set_alive()
c.alive
# True

6. reduce

函数的作用是将一个序列归纳为一个输出reduce(function, sequence, startValue)

from functools import reducel = range(1,50)
print(reduce(lambda x,y:x+y, l))
# 1225

7. singledispatch

单分发器,用于实现泛型函数。根据单一参数的类型来判断调用哪个函数。

from functools import singledispatch
@singledispatch
def fun(text):print('String:' + text)@fun.register(int)
def _(text):print(text)@fun.register(list)
def _(text):for k, v in enumerate(text):print(k, v)@fun.register(float)
@fun.register(tuple)
def _(text):print('float, tuple')
fun('i am is hubo')
fun(123)
fun(['a','b','c'])
fun(1.23)
print(fun.registry) # 所有的泛型函数
print(fun.registry[int])    # 获取int的泛型函数
# String:i am is hubo
# 123
# 0 a
# 1 b
# 2 c
# float, tuple
# {<class 'object'>: <function fun at 0x106d10f28>, <class 'int'>: <function _ at 0x106f0b9d8>, <class 'list'>: <function _ at 0x106f0ba60>, <class 'tuple'>: <function _ at 0x106f0bb70>, <class 'float'>: <function _ at 0x106f0bb70>}
# <function _ at 0x106f0b9d8>

8. singledispatchmethod

与泛型函数类似,可以编写一个使用不同类型的参数调用的泛型方法声明,根据传递给通用方法的参数的类型,编译器会适当地处理每个方法调用。

class Negator:@singledispatchmethoddef neg(self, arg):raise NotImplementedError("Cannot negate a")@neg.registerdef _(self, arg: int):return -arg@neg.registerdef _(self, arg: bool):return not arg

9. total_ordering

它是针对某个类如果定义了ltlegtge这些方法中的至少一个,使用该装饰器,则会自动的把其他几个比较函数也实现在该类中

from functools import total_orderingclass Person:# 定义相等的比较函数def __eq__(self,other):return ((self.lastname.lower(),self.firstname.lower()) == (other.lastname.lower(),other.firstname.lower()))# 定义小于的比较函数def __lt__(self,other):return ((self.lastname.lower(),self.firstname.lower()) < (other.lastname.lower(),other.firstname.lower()))p1 = Person()
p2 = Person()p1.lastname = "123"
p1.firstname = "000"p2.lastname = "1231"
p2.firstname = "000"print p1 < p2  # True
print p1 <= p2  # True
print p1 == p2  # False
print p1 > p2  # False
print p1 >= p2  # False

10. update_wrapper

使用 partial 包装的函数是没有__name____doc__属性的。
update_wrapper 作用:将被包装函数的__name__等属性,拷贝到新的函数中去。

from functools import update_wrapper
def wrap2(func):def inner(*args):return func(*args)return update_wrapper(inner, func)@wrap2
def demo():print('hello world')print(demo.__name__)
# demo

11. wraps

warps 函数是为了在装饰器拷贝被装饰函数的__name__
就是在update_wrapper上进行一个包装

from functools import wraps
def wrap1(func):@wraps(func)   # 去掉就会返回innerdef inner(*args):print(func.__name__)return func(*args)return inner@wrap1
def demo():print('hello world')print(demo.__name__)
# demo

参考文献

Python-functools详解 - 知乎

Python的functools模块_Python之简的博客-CSDN博客_functools

Python的Functools模块简介_函数

cached_property/缓存属性_小二百的博客-CSDN博客

盖若 gairuo.com

Python库functools详解相关推荐

  1. Python爬虫之selenium库使用详解

    Python爬虫之selenium库使用详解 本章内容如下: 什么是Selenium selenium基本使用 声明浏览器对象 访问页面 查找元素 多个元素查找 元素交互操作 交互动作 执行JavaS ...

  2. python时间函数详解_Python:Numpy库基础分析——详解datetime类型的处理

    原标题:Python:Numpy库基础分析--详解datetime类型的处理 Python:Numpy库基础分析--详解datetime类型的处理 关于时间的处理,Python中自带的处理时间的模块就 ...

  3. python可以处理多大的数据_科多大数据之Python基础教程之Excel处理库openpyxl详解...

    原标题:科多大数据之Python基础教程之Excel处理库openpyxl详解 科多大数据小课堂来啦~Python基础教程之Excel处理库openpyxl详解 openpyxl是一个第三方库,可以处 ...

  4. python的excell库_扣丁学堂Python基础教程之Excel处理库openpyxl详解

    扣丁学堂Python基础教程之Excel处理库openpyxl详解 2018-05-04 09:49:49 3197浏览 openpyxl是一个第三方库,可以处理xlsx格式的Excel文件.pipi ...

  5. Python标准库time详解

    Python标准库time详解 1.time库 时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量 结构化时间(struct_time ...

  6. Python BS4解析库用法详解

    Python BS4解析库用法详解 Beautiful Soup 简称 BS4(其中 4 表示版本号)是一个 Python 第三方库,它可以从 HTML 或 XML 文档中快速地提取指定的数据.Bea ...

  7. Python bs4解析库使用详解

    今天继续给大家介绍Python 爬虫相关知识,本文主要内容是Python bs4解析库使用详解. 一.Python bs4库简介与安装 bs4是Python的一个第三方库,主要用于从HTML或者是XM ...

  8. Python中lambda详解(包括内置函数map、reduce、filter、sorted、max)

    文章目录 一.lambda是什么? 1.lambda语法 2.语法详解 二.lambda的使用 1.定义 2.调用 3.替换 4.作返回值 三.lambda作参数 1.map函数 2.reduce函数 ...

  9. windows上安装Anaconda和python的教程详解

    一提到数字图像处理编程,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1.不开源,价格贵 2.软件容量大.一般3G以上,高版本甚至达5G以上. 3.只能做研究,不易转化成软件. 因 ...

最新文章

  1. 新基建来势汹汹,开发者如何捍卫其安全?
  2. hdu1686 最大匹配次数 KMP
  3. Mybatis中的@Param注解
  4. aix系统服务器限制ftp访问,AIX 限制ftp用户只能访问其主目录
  5. 创建 Robotium 测试工程
  6. Python实战——2048
  7. linux 添加新的系统调用,如何在Linux中添加新的系统调用
  8. Rancher 2.2.2 Stable版本发布,生产可用!
  9. cmmi证书查询(cmmi认证查询网站)
  10. 【博弈论】耶鲁大学公开课--博弈论Problem Set 1--Solution
  11. QQ在线客服代码演示-asp源代码
  12. 从零开始iOS8编程【HelloWorld】
  13. Linux命令之新增组groupadd
  14. 如何清除浏览器历史记录-在Chrome,Firefox和Safari中删除浏览历史记录
  15. 2003服务器密码怎么修改密码,2003服务器设置密码
  16. 2022哪些蓝牙耳机适合学生党?适合学生党的平价蓝牙耳机推荐
  17. 32岁的程序员被裁,java宿舍管理系统源码jsp
  18. 根据身高体重计算BMI指数,判断您是否健康。
  19. 学习OpenCV——grabcut
  20. Flink(二十三)—— 流计算框架 Flink 与 Storm 的性能对比

热门文章

  1. 欧奈尔杯柄形态选股公式,突破杯柄高点发出信号
  2. 计算九连环需要多少步解下来的方法
  3. 如何更改照片的像素和大小?更改图片大小的方法
  4. RK3568平台开发系列讲解(系统优化篇)常见CPU性能问题
  5. Java - 异步处理
  6. 超强且极具内涵的电影经典台词
  7. java 8 排序_Java 八大排序实现
  8. licode pre-v7.3开启屏幕共享功能
  9. IntelliJ IDEA-配置文件位置
  10. RESTful风格是什么