Use partial change method default parameter instance in Python

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.
Copy CodeThe code is as follows:


#!/usr/bin/env python
#-*-Coding:utf-8-*-
#python2.7x
#partial. py
#authror: Orangleliu

'''
Partial in Functools 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 a parameter that does not have a default value
'''
def foo (a,b=0):
'''
int add '
'''
Print A + b

#user default Argument
Foo (1)

#change default Argument once
Foo (+)

#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 have three read-only attributes
I'll list them
'''
Print Foo2.func
Print Foo2.args
Print Foo2.keywords
Print dir (foo2)

# #默认情况下partial对象是没有 __name__ __doc__ property, use Update_wrapper to add attributes 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__
'''
Changed the document information to Foo.
'''

  • 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.