[Python] Partial change method default parameter

Source: Internet
Author: User

In the Python standard library, there are many functools in the library, and partial objects is one of them, which is the modification of the default value of the method parameter.

Let's look at the simple application test below.

#!/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 of the parameter 2 to the original parameter does not have the default value to increase the default value ' def foo (a,b=0): ' ' int add ' ' Print a + b#user default Argumentfoo (1) #change default argument oncefoo (#change function ' s default argument, and You can use the function with new argumentimport functoolsfoo1 = functools.partial (foo, b=5) #change "B" default argument Foo1 (1) foo2 = functools.partial (foo, a=10) #give "a" Default Argumentfoo2 () "Foo2 is a partial object,it only have three R Ead-only Attributesi would list them "print Foo2.funcprint foo2.argsprint foo2.keywordsprint dir (foo2) # # By default, the partial object is not __name__ __doc__ property, using Update_wrapper to add attributes from the original method to the partial object in 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__ "changed the document information to Foo" 


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

This article is derived from"Orangleliu Notebook" Blog, be sure to keep this source http://blog.csdn.net/orangleliu/article/details/38656585

Related Article

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.