In the Python standard library, there are many functools in the library, and partial objects is one of them, which is the modification of the default value of the method parameter.
Let's look at the simple application test below.
Copy CodeThe code is as follows:
#!/usr/bin/env python
#-*-Coding:utf-8-*-
#python2.7x
#partial. py
#authror: Orangleliu
'''
Partial in Functools can be used to change a method default parameter
1 Change the default value of the original default value parameter
2 Add a default value to a parameter that does not have a default value
'''
def foo (a,b=0):
'''
int add '
'''
Print A + b
#user default Argument
Foo (1)
#change default Argument once
Foo (+)
#change function ' s default argument, and you can use the function with new argument
Import Functools
foo1 = Functools.partial (foo, b=5) #change "B" default argument
Foo1 (1)
Foo2 = Functools.partial (foo, a=10) #give "a" default argument
Foo2 ()
'''
Foo2 is a partial object,it only have three read-only attributes
I'll list them
'''
Print Foo2.func
Print Foo2.args
Print Foo2.keywords
Print dir (foo2)
# #默认情况下partial对象是没有 __name__ __doc__ property, use Update_wrapper to add attributes from the original method to the partial object
Print foo2.__doc__
'''
Execution Result:
Partial (func, *args, **keywords)-new function with partial application
Of the given arguments and keywords.
'''
Functools.update_wrapper (Foo2, foo)
Print foo2.__doc__
'''
Changed the document information to Foo.
'''