In Python's standard library, there are many encapsulation features in the Functools library that operate on methods, and partial objects is one of them that can implement changes to the default values of method parameters. This article describes this feature as an example code.
Here is a simple example of an application test. The specific code is as follows:
#!/usr/bin/env python #-*-coding:utf-8-*-#python2 7x #partial. py #authror: Orangleliu ' functools can be used to change a A method default parameter 1 changes the default value of the original default value of 2 to add the default value to the parameter with no default value ' def foo (a,b=0): ' ' int add ' ' Print a + b #user default Argume NT Foo (1) #change default argument once foo (1,1) #change function ' s default argument, and can use the function with New argument import Functools foo1 = functools.partial (foo, b=5) #change "B" Default argument foo1 (1) foo2 = FUNCTOOLS.P Artial (foo, a=10) #give "a" Default argument Foo2 () ' ' Foo2 is a partial object,it only has three read-only I 'll list them ' ' Print foo2.func print foo2.args print foo2.keywords print dir (foo2) # #默认情况下partial对象是没有 __name__ __do c__ property, using Update_wrapper to add a property from the original method to the partial object print foo2.__doc__ ' execution result: partial (func, *args, **keywords)-New Functio
N with partial application of the given arguments and keywords. ' Functools.update_wrapper (Foo2, foo) print foo2.__doc__ ' modified to Foo's document information '
This way, if we use a method that always requires a few default parameters, do a package and then do not have to set the same parameters each time.
It is hoped that the method described in this paper can be used for reference and helpful to everyone's Python programming.