Use partial in Python to change the default parameter instance
This article describes how to use partial to change the default parameter instance in Python. This article describes how to use the instance directly. The Code contains detailed comments. For more information, see
The functools library in the Python standard library contains many methods that are encapsulated with operations. partial Objects is one of them, which modifies the default values of method parameters.
Next let's take a look at simple application testing.
The Code is as follows:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Python2.7x
# Partial. py
# Authror: orangleliu
'''
In functools, Partial can be used to change the default parameters of a method.
1. Change the default value of the original default value parameter.
2. Add a default value to a parameter without a 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, the partial object does not have the _ name _ doc _ attribute. Use update_wrapper to add the attribute 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 the document information for foo.
'''