Python implements partial change method default parameter

  • 2020-04-02 13:54:25
  • OfStack

In Python's standard library, the functools library has many functions that encapsulate operations on methods, partial Objects being one of them, which can modify the default values of method parameters. This article illustrates this functionality with example code.

Let's look at a simple application test example. The specific code is as follows:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#partial.py
#authror: orangleliu

'''
functools  In the Partial Can be used to change a method's default parameter 
1  Change the default value of the original default parameter 
2  Adds a default value to an argument that previously had no default value 
'''
def foo(a,b=0) :
  '''
  int add'
  '''
  print a + b

#user default argument
foo(1)

#change default argument once
foo(1,1)

#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 has three read-only attributes
i will list them
'''
print foo2.func
print foo2.args
print foo2.keywords
print dir(foo2)

## By default partial The object is not  __name__ __doc__  Attributes, using update_wrapper  Add attributes to from the original method partial  In the object 
print foo2.__doc__
'''
 Execution results: 
partial(func, *args, **keywords) - new function with partial application
  of the given arguments and keywords.
'''

functools.update_wrapper(foo2, foo)
print foo2.__doc__
'''
 Modified to foo Document information 
'''

So if we use a method that always requires several parameters by default, we can do a wrapper and then we don't have to set the same parameters every time.

It is hoped that the method described in this paper can be used for reference and help in Python programming.


Related articles: