Use partial to change method default parameter instances in Python

Source: Internet
Author: User

This article mainly introduces Python use partial change method default parameter instance, this article directly gives the use instance, the code contains the detailed annotation, the need friend may refer to the next

Partial objects is one of a number of functools libraries in the Python standard library that have an operational encapsulation, and he modifies the default values of method parameters.

Let's look at the simple application test below.

The code is as follows:

#!/usr/bin/env python



#partial. py

#authror: Orangleliu


Functools partial 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 an argument that has 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 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

I'll list them


Print Foo2.func

Print Foo2.args

Print Foo2.keywords

Print dir (foo2)

# #默认情况下partial对象是没有 __name__ __doc__ property, using Update_wrapper to add attributes from the original method to the partial 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__


Modify the Document information for Foo


Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.