美文网首页数据工程师
functools 模块详解

functools 模块详解

作者: 苟雨 | 来源:发表于2017-03-08 19:28 被阅读24次

functool.reduce 方法是迭代的应用传入的方法用前面得到的值来作为输入,所以方法最好有两个以上的变量,不然就不能迭代了

import functools
def ad(x,y):
    return x*y
​
functools.reduce(ad,[2,3,4])
24

functools.partial 函数可以为函数提供定义好的输入变量,就像是函数的预定义变量一样,

In [27]:

def hello(one,two,three):
    if one:
        return two
    else:
        return three
    
par_func = functools.partial(hello,two='yes',three='no')
par_func(1)
Out[27]:
'yes'

functools.wraps 用这个函数定义函数的包装器,

In [33]:

from functools import wraps 
def my_decorator(f):
    @wraps(f)
    def wraper(*args,**kwds):
        print('calling decorators now')
        return f(*args,**kwds)
    return wraper
​
@my_decorator
def use_decorator():
    print('function use decotator')
    
use_decorator()
    
calling decorators now
function use decorator

functools.total_ordering 定义类的比较方式

In [35]:

from functools import total_ordering
@total_ordering
class Student:
    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()))
​

相关文章

  • functools 模块详解

    functool.reduce 方法是迭代的应用传入的方法用前面得到的值来作为输入,所以方法最好有两个以上的变量,...

  • functools模块

    一.update_wrapper 该函数用于更新包装函数(wrapper),使它看起来像被包装的原函数一样。该函数...

  • functools模块

    1 functools函数 functools模块用于高阶函数:作用与或者返回其它函数的函数。一般来说,对于该模块...

  • functools

    functools模块里存放的是一些工具函数,在使用前需要导入functools模块,在python3.X中,可以...

  • Python @cache 简化无限缓存

    Python 内置模块 functools 提供的高阶函数 @functools.cache 是简单轻量级无长度限...

  • 那些Python方法---reduce()

    python3中reduce被放到了functools模块,所以用之前需要导入 from functools im...

  • Python 模块简介 -- functools

    Python 的 functools 模块可以说主要是为函数式编程而设计,用于增强函数功能。 functools....

  • Python functools 模块

    functools 是 Python 中很简单但也很重要的模块,主要是一些 Python 高阶函数相关的函数。 该...

  • functools模块使用

    functools.partial作用是在真正调用一个函数之前给这个函数的部分参数赋值,并返回配置好了这些参数的一...

  • python 模块 - functools

    functools 模块应用于高阶函数,即参数或(和)返回值为其他函数的函数。通常来说,此模块的功能适用于所有可调...

网友评论

    本文标题:functools 模块详解

    本文链接:https://www.haomeiwen.com/subject/gucigttx.html