Use partial to change method default parameter instances in Python

Source: Internet
Author: User
Tags in python

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

#-*-Coding:utf-8-*-

#python2.7x

#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

'''

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.