jjzjj

Python库functools详解

瞻邈 2023-07-04 原文

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 a
    property cached on the instance.
    Optional ``name`` argument allows you to make cached properties of other
    methods. (e.g.  url = cached_property(get_absolute_url, name='url') )
    """
    def __init__(self, func, name=None):
        # print(f'f: {id(func)}')
        self.func = func
        self.__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 self
        res = instance.__dict__[self.name] = self.func(instance)
        return res
 
 
class F00():
    @cached_property
    def test(self):
        # cached_property 将会把每个实例的属性存储到实例的__dict__中, 实例获取属性时, 将会优先从__dict__中获取,则不会再次调用方法内部的过程
        print(f'运行test方法内部过程')
        return 3
    
    @property
    def t(self):
        print('运行t方法内部过程')
        return 44
 
 
f = 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 n
    return fib(n-1) + fib(n-2)
print([fib(n) for n in range(10)])
fib.cache_clear()   # 清空缓存

4. partial

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

from functools import partial

int2 = 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 partialmethod

class Cell:
    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)

    print(type(partialmethod(set_state, False)))
    # <class 'functools.partialmethod'>

c = Cell()
c.alive
# False

c.set_alive()
c.alive
# True

6. reduce

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

from functools import reduce

l = 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:
    @singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(self, arg: int):
        return -arg

    @neg.register
    def _(self, arg: bool):
        return not arg

9. total_ordering

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

from functools import total_ordering

class 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)	# 去掉就会返回inner
	def 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 - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  3. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  4. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  5. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  6. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

  7. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  8. Python 刷Leetcode题库,顺带学英语单词(31) - 2

    ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem

  9. python - 是否可以使用 Ruby 或 Python 禁用 anchor /引用来发出有效的 YAML? - 2

    是否可以在PyYAML或Ruby的Psych引擎中禁用创建anchor和引用(并有效地显式列出冗余数据)?也许我在网上搜索时遗漏了一些东西,但在Psych中似乎没有太多可用的选项,而且我也无法确定PyYAML是否允许这样做.基本原理是我必须序列化一些数据并将其以可读的形式传递给一个不是真正的技术同事进行手动验证。有些数据是多余的,但我需要以最明确的方式列出它们以提高可读性(anchor和引用是提高效率的好概念,但不是人类可读性)。Ruby和Python是我选择的工具,但如果有其他一些相当简单的方法来“展开”YAML文档,它可能就可以了。 最佳答案

  10. .net - .NET 将如何影响 Python 和 Ruby 应用程序? - 2

    我很好奇.NET将如何影响Python和Ruby应用程序。用IronPython/IronRuby编写的应用程序是否会非常特定于.NET环境,以至于它们实际上将变得特定于平台?如果他们不使用任何.NET功能,那么IronPython/IronRuby相对于非.NET同类产品的优势是什么? 最佳答案 我不能说任何关于IronRuby的东西,但是大多数Python实现(如IronPython、Jython和PyPy)都试图尽可能忠实于CPython实现。不过,IronPython正在迅速成为这方面的佼佼者之一,并且在PlanetPyth

随机推荐