#-*-Coding: UTF-8 -*-
# Python: 2.x
_ Author _ = 'admin'
# Functools: Management Function Tool
# Function: functions used to process other functions
# Version: 2.5 and later
# Used to adjust or extend functions and other callable objects without rewriting
# Modifier: The main tool is partial, which is used for packaging. An object with default parameters can be called back. The object itself can be called back and can be viewed as an original function. It is identical with the original function and can provide additional positions or named parameters during the call, you can use partial instead of the default parameter provided by Lambda. Some parameters are not specified.
# Partial object
Import functools
Def myfunc (a, B = 2 ):
'''Docstring for myfunc ().'''
Print 'called myfunc with: ', (A, B)
Return
Def show (name, F, is_partial = false ):
Print Name
Print F
If not is_partial:
Print F. _ name __
If is_partial:
Print F. func
Print F. ARGs
Print F. Keywords
Return
Show ('myfunc', myfunc)
Myfunc ('A', 3)
Print
P1 = functools. Partial (myfunc, B = 4)
Show ('partial with named default', P1, true)
P1 ('Passing ')
P1 ('override B ', B = 5)
# P1 () # typeerror: myfunc () takes at least 1 argument (1 given)
# Retrieving Function Attributes
# By default, the partial object does not have the _ name _ or _ Doc _ attribute. Without these attributes, the modifier function is more difficult to debug. You can use update_wrapper () to add the original function attribute or to the oartial object.
Def myfunc1 (a, B = 2 ):
'''Docstring for myfunc ().'''
Print 'called myfunc with: ', (A, B)
Return
Def show2 (n, f ):
Print n
Print F
Print '_ name __'
Try:
Print F. _ name __
T attributeerror, s:
Print 'no _ name _ ', S
Print repr (F. _ Doc __)
Print
Return
Show2 ('myfunc1 ', myfunc1)
P1 = functools. Partial (myfunc1, B = 4)
Show2 ('raw wrapper ', P1)
Print functools. wrapper_assignments
Print functools. wrapper_updates
Functools. update_wrapper (P1, myfunc1)
Show2 ('updated wrapper', P1)
# Other callable # paryisl applies to any callable object, not just individual functions
Class myclass (object ):
Def Method1 (self, a, B = 2 ):
Print self, a, B
Return
Def methond2 (self, c, d = 5 ):
Print self, c, d
Return
Wrapp = functools. Partial (methond2, 'wrapped C ')
Functools. update_wrapper (wrapp, methond2)
Def _ call _ (self, X, Z = 6 ):
Print self, X, Z
Return
Def show_update (n, f ):
Print n
Print F
Print '_ name __'
Try:
Print F. _ name __
T attributeerror, s:
Print 'no _ name _ ', S
Print repr (F. _ Doc __)
Print
Return
O = myclass ()
Show_update ('method1 straight ', O. Method1)
O. Method1 ('on default for a', B = 3)
Print
P1 = functools. Partial (O. Method1, B = 4)
Functools. update_wrapper (P1, O. Method1)
Show_update ('method1 wrarer', P1)