7.2 functools--higher-order functions and callable objects

Source: Internet
Author: User

This module mainly provides high-order functions and callable objects.

Functools.cmp_to_key (func)

Convert the comparison function of the old type to a key-value function. Mainly used to convert Python version 2 of the function parameters, such as in the function sorted (),miin (), Max (),heapq.nlargest ().

Example:

#python 3.4

From functools Import *

L = [2, 8, 1, 3]

def num_cmp (x, y):

return x-y

R = Sorted (l, key = Cmp_to_key (NUM_CMP))

Print (R)

The resulting output is as follows:

[1, 2, 3, 8]

@functools. Lru_cache (maxsize=128, Typed=false)

The Lru_cache function is an adorner function, which is primarily used to cache the results of recent calls, which increases the efficiency of function calls and does not have to be recalculated every time. The parameter maxsize is the number of times the cache is set to none when the cache is not throttled, but it consumes more memory; parameter typed is used to store function return values in different types, if set to True to differentiate, such as F (3) and F (3.0) Will distinguish between different places to save, and set to False to not make such a distinction to save. Because the cache results are saved using a dictionary, some positional and key parameters need to be hash -saved.

Example:

#python 3.4

From functools Import *

@lru_cache (Maxsize=none)

def fib (n):

If n < 2:

return n

return fib (n-1) + fib (n-2)

R = [FIB (n) for n in range (16)]

Print (R)

Print (Fib.cache_info ())

The resulting output is as follows:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

Cacheinfo (hits=28, misses=16, Maxsize=none, currsize=16)

@functools. total_ordering

Provides a class that has an adorner for the comparison method. For example, if you want to write a sort class, you need to write more than, equal to, less than the comparison implementation, if each overload to write more code, and this adorner provides a way, as long as the implementation of their own needs of the comparison function, the other using the default implementation of the decoration.

Example:

@total_ordering

Class Student:

def _is_valid_operand (self, Other):

Return (Hasattr (Other, "LastName") and

Hasattr (Other, "FirstName"))

def __eq__ (self, Other):

If not Self._is_valid_operand (other):

Return notimplemented

Return ((Self.lastname.lower (), self.firstname.lower ()) = =

(Other.lastname.lower (), Other.firstname.lower ()))

def __lt__ (self, Other):

If not Self._is_valid_operand (other):

Return notimplemented

Return ((Self.lastname.lower (), Self.firstname.lower ()) <

(Other.lastname.lower (), Other.firstname.lower ()))

Functools.partial (func, *args, **keywords)

A function object that returns a fixed partial parameter. For example, to call a function has five parameters, but in the use of the process found that there are three parameters that need to be fixed, do not change, you can use this method to bind these parameters, so as to achieve simplification, do not let the subsequent code to modify.

Example:

#python 3.4

From functools Import *

def add (A, B):

Return a + b

R = Partial (add, 10)

Print (R)

Print (R (1)) #10 + 1

Print (R (2)) #10 + 2

The resulting output is as follows:

Functools.partial (<function add at 0x02d879c0>, 10)

11

12

Class Functools.partialmethod (func, *args, **keywords)

This function is the same as the function above, except that this function only binds parameters to the methods in the class.

Example:

#python 3.4

From functools Import *

Class Cell (object):

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)

c = Cell ()

Print (c.alive)

C.set_alive ()

Print (c.alive)

The resulting output is as follows:

False

True

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

The function functions of a two parameters are applied to a sequence for iterative operation. For example , reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) will be calculated as follows:(((((((((() +3) +4). Its implementation is equivalent to the following code:

def reduce (function, iterable, Initializer=none):

it = iter (iterable)

If initializer is None:

Value = Next (IT)

Else

Value = initializer

For element in it:

Value = function (value, Element)

return value

Example:

#python 3.4

From functools Import *

def statistics (DIC,K):

If not K in DIC:

DIC[K] = 1

Else

DIC[K] +=1

return dic

LST = [1, 2, 3, 4]

Print (Reduce (statistics, LST, {}))

The resulting output is as follows:

{1:1, 2:1, 3:1, 4:1}

@functools. Singledispatch (default)

This adorner is used to implement functions that overload multiple types. For example, the same function name, for different types have different function implementation.

Example:

#python 3.4

From functools Import *

@singledispatch

def fun (arg, verbose = False):

If verbose:

Print (' Singledispatch: ', end = ')

Print (ARG)

@fun. Register (list)

def _ (arg, verbose = False):

If verbose:

Print (' list: ')

For I, Elem in Enumerate (ARG):

Print (I, elem)

Fun (verbose = True)

Fun ([1, 2, 3], verbose = True)

The resulting output is as follows:

singledispatch:100

List

0 1

1 2

2 3

Functools.update_wrapper (wrapper, wrapped, assigned=wrapper_assignments, updated=wrapper_updates)

The update function wapper , like the wrapped function, primarily shares the same description string.

Example:

#python 3.4

From functools Import *

def updatetest (fun):

def living (*args, **kw):

Return Fun (*args, **kw) + ' best '

Return Update_wrapper (Living, fun)

@updateTest

Def caimouse ():

"Blog.csdn.net/caimouse"

Return ' Python '

Print (Caimouse ())

Print (caimouse.__doc__)

The resulting output is as follows:

Python Best

Blog.csdn.net/caimouse

@functools. Wraps (wrapped, assigned=wrapper_assignments, updated=wrapper_updates)

This function encapsulates the function above and provides the same functionality.

Example:

#python 3.4

From functools Import *

Def my_decorator (f):

@wraps (f)

def wrapper (*args, **kwds):

Print (' Calling decorated function ')

Return f (*args, **kwds)

Return wrapper

@my_decorator

def example ():

"" "DocString" ""

Print (' Called example function ')

Example ()

Print (example.__doc__)

The resulting output is as follows:

Calling decorated function

called Example function

DocString

Cai Junsheng qq:9073204 Shenzhen

7.2 functools--higher-order functions and callable objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.