Functools module: Tools for managing functions
Partial object: wrapping the original function, providing a default value
Import functools# original function def myfunc (a, b=2): """docstring for MyFunc ()."""Print ('called MyFunc with:', a, b)return# output function def show_details (name, f, is_partial=False): print (name) print (f)ifnot Is_partial:print (f.__name__)ifis_partial:print (f.func) Print (f.args) print (f.keywords)return# show_details ('MyFunc', Myfunc) # myfunc ('a',3) P1= Functools.Partial(myfunc, b=4) # The function show_details after wrapping ('partial with named', p1, True) p1 ('Passing a'# Call the wrapper after the function P1 ('Override B', b=5)
Copy the properties of the original function to the partial object
Functools.update_wrapper (p1, Myfunc) # comment out this line, run error print (p1.__name__) print (p1.__doc__)
Wrapping a function of an instance object
classMyClass (Object): def method (self, a, B=2): """docstring for method ()."""Print ('called method With:', a, b)returno=MyClass () p1= Functools.Partial(o.method, b=4) Show_details ('partial with named', p1, True) functools.update_wrapper (p1, o.method) print (p1.__name__) print (p1.__doc__)
@functools. Wraps Decorators
def simple_decorator (f): @functools. wraps (f) def decorated (a='decorated' , b=1): print (a, b) f (a,b =b) return return = simple_decorator (myfunc) print (wrapped.__name__) print (wrapped.__doc__)
@functools. total_ordering
To add a rich comparison method to a class, the class must provide __eq__ and another rich comparison method
@functools. Cmp_to_key (cmp_obj)
Python Standard Library--functools module