This article mainly introduces Python functools module Learning Summary, this article explains Functools.partial, Functool.update_wrapper, Functool.wraps, Functools.reduce, Functools.cmp_to_key, Functools.total_ordering and other methods of use of examples, need friends can refer to the following
Document Address
Functools.partial
Role:
Functools.partial allows us to "redefine" the function signature by wrapping the technique
Wrapping a callable object with some default parameters, returning the result is a callable object and can be treated like the original object
Freeze part function position function or keyword parameter, simplify function, less flexible function parameter call
The code is as follows:
#args/keywords Call Partial time argument
def partial (func, *args, **keywords):
def newfunc (*fargs, **fkeywords):
Newkeywords = Keywords.copy ()
Newkeywords.update (Fkeywords)
return func (* (args + Fargs), **newkeywords) #合并, invoke the original function, with the partial argument
Newfunc.func = Func
Newfunc.args = args
Newfunc.keywords = Keywords
Return Newfunc
Statement:
The code is as follows:
Urlunquote = Functools.partial (urlunquote, encoding= ' latin1 ')
When calling Urlunquote (args, *kargs)
Equivalent to Urlunquote (args, *kargs, encoding= ' latin1 ')
e.g:
The code is as follows:
Import Functools
def add (A, B):
Return a + b
Add (4, 2)
6
PLUS3 = Functools.partial (Add, 3)
PLUS5 = Functools.partial (Add, 5)
PLUS3 (4)
7
PLUS3 (7)
10
PLUS5 (10)
15
Application:
Typically, a function is invoked with all the necessary arguments when it executes.
Then, sometimes the parameters can be learned in advance of the function being invoked.
In this case, one or more parameters of a function can be used beforehand so that the function can be invoked with fewer arguments.
Functool.update_wrapper
The default partial object has no __name__ and __doc__, which is very difficult to debug for an adorner function. Use Update_wrapper () to copy or join an existing partial object from the original object
It can copy the __name__, module, __doc__, and __dict__ of the encapsulated function to the encapsulation function (module level constants Wrapper_assignments, wrapper_updates)
The code is as follows:
>>> Functools. Wrapper_assignments
(' __module__ ', ' __name__ ', ' __doc__ ')
>>> Functools. Wrapper_updates
(' __dict__ ',)
This function is mainly used in the adorner function, the adorner return function reflects the function definition of the wrapper function rather than the original function definition
The code is as follows:
#!/usr/bin/env python
# Encoding:utf-8
def wrap (func):
def call_it (*args, **kwargs):
"" "Wrap Func:call_it" ""
print ' Before call '
return func (*args, **kwargs)
Return Call_it
@wrap
def hello ():
"" "Say Hello" ""
print ' Hello World '
From Functools import Update_wrapper
def wrap2 (func):
def call_it (*args, **kwargs):
"" "Wrap Func:call_it2" ""
print ' Before call '
return func (*args, **kwargs)
Return Update_wrapper (Call_it, func)
@wrap2
Def Hello2 ():
"" "Test Hello" ""
print ' Hello world2 '
if __name__ = = ' __main__ ':
Hello ()
Print hello.__name__
Print hello.__doc__
Print
Hello2 ()
Print hello2.__name__
Print hello2.__doc__
Get the result:
The code is as follows:
Before call
Hello World
Call_it
Wrap Func:call_it
Before call
Hello World2
Hello2
Test Hello
Functool.wraps
Call function Adorner partial (Update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated) shorthand
The code is as follows:
From Functools Import Wraps
def wrap3 (func):
@wraps (func)
def call_it (*args, **kwargs):
"" "Wrap Func:call_it2" ""
print ' Before call '
return func (*args, **kwargs)
Return Call_it
@wrap3
Def Hello3 ():
"" "Test Hello 3" ""
print ' Hello world3 '
Results
The code is as follows:
Before call
Hello world3
Hello3
Test Hello 3
Functools.reduce
The code is as follows:
Functools.reduce (function, iterable[, initializer])
Equivalent to built-in functions reduce ()
The reason for this is to make the code more compatible (PYTHON3)
Functools.cmp_to_key
Functools.cmp_to_key (func)
Converts the old tip function into a key function in a method that accepts a key function (such as sorted (), Min (), Max (), Heapq.nlargest (), Heapq.nsmallest (), Itertools.groupby ( ))
A comparison function that receives two arguments, is less than, returns a negative number, equals, returns 0, greater than the returned integer
Key function, which receives a parameter that returns the position of the parameter in the desired sequence.
For example:
The code is as follows:
Sorted (iterable, Key=cmp_to_key (Locale.strcoll)) # Locale-aware sort order
Functools.total_ordering
The code is as follows:
Functools.total_ordering (CLS)
This adorner is added at the time of python2.7, it is for a class if the __lt__, Le, GT, __ge__ These methods are defined at least one, the adorner, you will automatically put several other comparison functions are also implemented in the class
The code is as follows:
@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 ()))
Print dir (Student)
Get
The code is as follows:
[' __doc__ ', ' __eq__ ', ' __ge__ ', ' __gt__ ', ' __le__ ', ' __lt__ ', ' __module__ ']