This article mainly introduces how to change the default parameters of the partial method in Python. For more information, see the standard Python library. The functools library contains many encapsulation functions for methods, partial Objects is one of them, which can be used to modify the default value of a method parameter. This article describes this function using the instance code.
Next let's take a look at a simple application test instance. The Code is as follows:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# python2.7x # partial. py # authror: the Partial in orangleliu ''' functools can be used to change the default parameter of a method. 1. Change the default value of the original default parameter. 2. Add the default value '''def foo (, B = 0): '''int add''' print a + B # user default argumentfoo (1) # change default argument oncefoo (1, 1) # change function's default argument, and you can use the function with new argumentimport functoolsfoo1 = functools. partial (foo, B = 5) # change "B" default argumentfoo1 (1) foo2 = functools. partial (foo, a = 10) # give "a" default argumentfoo2 () ''' foo2 is a partial object, it only has three read-only attributesi will list them ''' print foo2.funcprint foo2.argsprint foo2.keywordsprint dir (foo2) # by default, the partial object does not have the _ name _ doc _ attribute, 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 _ ''' modified to the foo Document Information '''
In this way, if we use a method that always requires several default parameters, we can first encapsulate it and don't need to set the same parameters every time.
I hope the methods described in this article will be of some reference and help value to everyone's Python program design.