Use partial in Python to change the default parameter instance

Source: Internet
Author: User

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.

'''

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.