Python functional Programming--partial function

Source: Internet
Author: User

1.1   Partial function

Python 's functools module provides a number of useful features, one of which is the partial function. It is important to note that the partial function here is not the same as the partial function in mathematical sense.

When we introduce the function parameters, we can reduce the difficulty of the function call by setting the default value of the parameter.

>>> Import Functools

>>> Int (' 123 ', base = 8)-- converted to 8 binary

83

>>> Int (' 123 ', base = +)-- converted into a binary

291

Functools.partial is helping us to create a biased function.

>>> def int2 (x, base = 2):

... return int (x, Base)

...

>>> int2 (' 11111111111111 ')

16383

>>> Import Functools

>>> int2 =functools.partial (int, base = 2)

>>> int2 (' 11111111111111 ')

16383

The function of functools.partial is to fix certain parameters of a function (that is, to set default values), to return a new function, and to call this new function is simpler.

when you create a partial function, you can actually receive the function object, *args and the **kw it 3 a parameter when passed in:

Int2 = functools.partial (int, base=2)

The keyword parameter base of the int () function is actually fixed , i.e.:

Int2 (' 10010 ')

Equivalent:

KW = {' base ': 2}

Int (' 10010 ', **kw)

Max2 = Functools.partial (max, 10)

will actually automatically add a portion of the *args to the left, namely:

MAX2 (5, 6, 7)

Equivalent:

args = (10, 5, 6, 7)

Max (*args)

The result is ten.


This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1821013

Python functional Programming--partial function

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.