Example analysis functools module function

Y2J
Release: 2017-05-09 14:54:09
Original
1626 people have browsed it

This article mainly introduces the common function analysis of the functools module in Python. It explains the usage of functools.cmp_to_key, functools.total_ordering, functools.reduce, functools.partial, functools.update_wrapper and functools.wraps respectively. Friends who need it You can refer to

The functools module that comes with Python provides some commonly used higher-order functions, which are special functions used to process other functions. In other words, you can use this module to process callable objects.

functools module functionOverview

  • ##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()

Syntax:

functools.cmp_to_key(func)

This function is used to convert the old comparison function into a keyword function.

Old-style comparison function: receives two parameters and returns the comparison result. If the return value is less than zero, the former is less than the latter, if the return value is greater than zero, the opposite is true, and if the return value is equal to zero, the two are equal.

Keyword function: receives a parameter and returns its corresponding comparable object. For example,

sort

ed(), min(), max(), heapq.nlargest(), heapq.nsm

allest(), itertools.groupby() can all be used as keywords function. In Python 3, there are many places that no longer support the old comparison functions. At this time, you can use cmp_to_key() for conversion.

Example:

sorted(iterable, key=cmp_to_key(cmp_func))
Copy after login

functools.total_ordering()

Syntax:

functools.total_ordering( cls)

This is a class decorator used to automatically implement comparison operations of classes.

We only need to implement the eq() method and any one of the following methods lt(), le(), gt(), ge() in the class, then total_ordering() can automatically help us implement it The remaining comparison operations.

Example:

@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()))
Copy after login

functools.reduce()

Syntax:

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

This function is the same as Python’s built-in reduce() function and is mainly used to write code that is compatible with Python 3.

functools.partial()

Syntax:

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

This function returns a partial object. The effect of calling this object is equivalent to calling the func function and passing in the positional parameters args and keyword parameters keywords. If the object is called with positional arguments, these arguments will be added to args. If keyword arguments are passed in, they will be added to keywords.

The equivalent implementation of the partial() function is roughly as follows:

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
Copy after login

partial() function is mainly used to "freeze" some parameters of a function, returning a parameter with fewer parameters and easier to use function object.

Example:

>>> 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
Copy after login

functools.update_wrapper()

Syntax:

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

This function is used to
update the

wrapper function (wrapper) so that it looks like the original function. The optional parameter is a tuple, the assigned tuple specifies the

attributes to be replaced directly with the value of the original function, and the updated tuple specifies the attributes to be updated against the original function. The default values ​​of these two parameters are module-level constants: WRAPPER_ASSIGNMENTS and WRAPPER_UPDATES respectively. The former specifies direct assignment of the name, module, and doc attributes of the wrapper function, while the latter specifies the update of the dict attribute of the wrapper function. This function is mainly used in the definition of decorator functions and is placed before the wrapping function. If the wrapper function is not updated, the metainformation of the decorated function will become the metainformation of the wrapper function, not the metainformation of the original function.

functools.wraps()

Syntax:

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

wraps() simplifies the call of the update_wrapper() function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned, updated=updated).

Example:

>>> 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;
Copy after login

If this function is not used, the function name in the example will become wrapper, and the documentation (docstring) of the original function example() will be lost.

【related suggestion】

1. Python free video tutorial

2. Python basic introductory tutorial

3. Python meets data collection video tutorial

The above is the detailed content of Example analysis functools module function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template