This module provides 3 interesting functions, which are described below for their usage.
The first is the partial function, which can rebind the optional parameters of the function to generate a callable partial object
- >>> Int (' ten') # is actually equivalent to int (' Ten ', base=10) and int (' Ten ', ten)
- Ten
- >>> Int (' ten ', 2) # is actually an abbreviation for int (' Ten ', base=2)
- 2
- >>> from functools import partial
- >>> int2 = partial (int, 2) # I didn't write base here, and it went wrong.
- >>> Int2 (' ten ')
- Traceback (most recent):
- File "<stdin>", line 1, in <module>
- Typeerror:an integer is required
- >>> int2 = partial (int, base=2) # bind the base parameter to the Int2 function
- >>> int2 (' ten ') # Now the default parameter base is set to 2
- 2
- >>> Int2 (' Ten ', 3) # without base, the result is wrong
- Traceback (most recent):
- File "<stdin>", line 1, in <module>
- typeerror:keyword parameter ' base ' was given by position and by name
- >>> Int2 (' Ten ', base=3)
- 3
- >>> Type (int2)
- <type ' functools.partial '>
As you can see, the only thing to note is that an optional parameter must write out the parameter name.
Next is the Update_wrapper function, which can copy the encapsulated function's __name__, __module__, __doc__, and __dict__ to the encapsulation function:
- #-*-coding:gbk-*-
-
- def thisisliving (fun):
- def Living (*args, **kw):
- return fun (*args, **kw) + ' Alive is eating. '
- return living
-
- @thisIsliving
- def whatisliving ():
- "What Is Alive"
- return ' Yes, what's the life? '
-
- Print whatisliving ()
- print whatisliving.__doc__
-
- print
-
- From functools import update_wrapper
- def thisisliving (fun):
- def Living (*args, **kw):
- return fun (*args, **kw) + ' Alive is eating. '
- return update_wrapper (living, fun)
-
- @thisIsliving
- def whatisliving ():
- "What Is Alive"
- return ' Yes, what's the life? '
-
- Print whatisliving ()
- print whatisliving.__doc__
Results:
Yes
, what's the life? To live is to eat.
None
Yes, what's the life? To live is to eat.
What is Alive
However, it is not much use, after all, just a few 4 lines to write the assignment statement.
Finally, the wraps function, which encapsulates the Update_wrapper, is also included:
[Python]View Plain Copy
- #-*-coding:gbk-*-
-
- From functools import wraps
-
- def thisisliving (fun):
- @wraps(fun)
- def Living (*args, **kw):
- return fun (*args, **kw) + ' Alive is eating. '
- return living
-
- @thisIsliving
- def whatisliving ():
- "What Is Alive"
- return ' Yes, what's the life? '
-
- Print whatisliving ()
- print whatisliving.__doc__
Python's Functools module