关于Python中functools模块函数解析

高洛峰
Libérer: 2017-03-13 09:15:30
original
1671 Les gens l'ont consulté

这篇文章主要介绍了关于Python中functools模块函数解析,分别讲解了functools.cmp_to_key,functools.total_ordering,functools.reduce,functools.partial,functools.update_wrapper和functools.wraps的用法,需要的朋友可以参考下

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))
Copier après la connexion

functools.total_ordering()

语法:

functools.total_ordering(cls)

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

我们只需要在类中实现 eq() 方法和以下方法中的任意一个 lt(), le(), gt(), ge(),那么 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()))
Copier après la connexion

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
Copier après la connexion

partial() 函数主要用于“冻结”某个函数的部分参数,返回一个参数更少、使用更简单的函数对象。

示例:


>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.doc = &#39;Convert base 2 string to an int.&#39;
>>> basetwo(&#39;10010&#39;)
18
Copier après la connexion

functools.update_wrapper()

语法:

functools.update_wrapper(wrapper, wrapped[, assigned][, updated])

该函数用于更新包装函数(wrapper),使它看起来像原函数一样。可选的参数是一个元组,assigned 元组指定要直接使用原函数的值进行替换的属性,updated 元组指定要对照原函数进行更新的属性。这两个参数的默认值分别是模块级别的常量:WRAPPER_ASSIGNMENTS 和 WRAPPER_UPDATES。前者指定了对包装函数的 name, module, doc 属性进行直接赋值,而后者指定了对包装函数的 dict 属性进行更新。

该函数主要用于装饰器函数的定义中,置于包装函数之前。如果没有对包装函数进行更新,那么被装饰后的函数所具有的元信息就会变为包装函数的元信息,而不是原函数的元信息。

functools.wraps()

语法:

functools.wraps(wrapped[, assigned][, updated])

wraps() 简化了 update_wrapper() 函数的调用。它等价于 partial(update_wrapper, wrapped=wrapped, assigned, updated=updated)。

示例:


>>> from functools import wraps
>>> def my_decorator(f):
...   @wraps(f)
...   def wrapper(*args, **kwds):
...     print &#39;Calling decorated function&#39;
...     return f(*args, **kwds)
...   return wrapper

>>> @my_decorator
... def example():
...   """Docstring"""
...   print &#39;Called example function&#39;

>>> example()
Calling decorated function 
Called example function 
>>> example.name
&#39;example&#39; 
>>> example.doc
&#39;Docstring&#39;
Copier après la connexion

如果不使用这个函数,示例中的函数名就会变成 wrapper ,并且原函数 example() 的说明文档(docstring)就会丢失。

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!