首页 > 编程 > Python > 正文

Python中functools模块函数解析

2020-02-23 04:25:29
字体:
来源:转载
供稿:网友

Python自带的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数。换言之,就是能使用该模块对可调用对象进行处理。

functools模块函数概览

functools.cmp_to_key(func) functools.total_ordering(cls) functools.reduce(function, iterable[, initializer]) functools.partial(func[, args][, *keywords]) functools.update_wrapper(wrapper, wrapped[, assigned][, updated]) functools.wraps(wrapped[, assigned][, updated])

functools.cmp_to_key()

语法:

functools.cmp_to_key(func) 

该函数用于将旧式的比较函数转换为关键字函数。

旧式的比较函数:接收两个参数,返回比较的结果。返回值小于零则前者小于后者,返回值大于零则相反,返回值等于零则两者相等。

关键字函数:接收一个参数,返回其对应的可比较对象。例如 sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby() 都可作为关键字函数。

在 Python 3 中,有很多地方都不再支持旧式的比较函数,此时可以使用 cmp_to_key() 进行转换。

示例:

sorted(iterable, key=cmp_to_key(cmp_func)) 

functools.total_ordering()

语法:

functools.total_ordering(cls) 

这是一个类装饰器,用于自动实现类的比较运算。

我们只需要在类中实现 __eq__() 方法和以下方法中的任意一个 __lt__(), __le__(), __gt__(), __ge__(),那么 total_ordering() 就能自动帮我们实现余下的几种比较运算。

示例:

@total_orderingclass 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.reduce()

语法:

functools.reduce(function, iterable[, initializer]) 

该函数与 Python 内置的 reduce() 函数相同,主要用于编写兼容 Python 3 的代码。

functools.partial()

语法:

functools.partial(func[, *args][, **keywords]) 

该函数返回一个 partial 对象,调用该对象的效果相当于调用 func 函数,并传入位置参数 args 和关键字参数 keywords 。如果调用该对象时传入了位置参数,则这些参数会被添加到 args 中。如果传入了关键字参数,则会被添加到 keywords 中。

partial() 函数的等价实现大致如下:

def partial(func, *args, **keywords):   def newfunc(*fargs, **fkeywords):    newkeywords = keywords.copy()    newkeywords.update(fkeywords)    return func(*(args + fargs), **newkeywords)  newfunc.func = func  newfunc.args = args  newfunc.keywords = keywords  return newfunc            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表