Python implements partial change method default parameter _python

Source: Internet
Author: User
Tags in python

In Python's standard library, there are many encapsulation features in the Functools library that operate on methods, and partial objects is one of them that can implement changes to the default values of method parameters. This article describes this feature as an example code.

Here is a simple example of an application test. The specific code is as follows:

#!/usr/bin/env python #-*-coding:utf-8-*-#python2 7x #partial. py #authror: Orangleliu ' functools can be used to change a A method default parameter 1 changes the default value of the original default value of 2 to add the default value to the parameter with no default value ' def foo (a,b=0): ' ' int add ' ' Print a + b #user default Argume NT 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.P  Artial (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__ __do c__ property, using Update_wrapper to add a property from the original method to the partial object print foo2.__doc__ ' execution result: partial (func, *args, **keywords)-New Functio
N with partial application of the given arguments and keywords. ' Functools.update_wrapper (Foo2, foo) print foo2.__doc__ ' modified to Foo's document information '

 

This way, if we use a method that always requires a few default parameters, do a package and then do not have to set the same parameters each time.

It is hoped that the method described in this paper can be used for reference and helpful to everyone's Python programming.

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.