Python Learning notes (11) Partial function

Source: Internet
Author: User

Excerpt: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 00143184474383175eeea92a8b0439fab7b392a8a32f8fa000

This article is completely used for personal review, invasion and deletion;

functools.partial is to help us create a biased function, without our own definition int2() , you can create a new function directly using the following code int2 :

Import Functools functools.partial (int, base=2)>>> int2 ('1000000')64>>> int2 ('  1010101')85

So, the simple functools.partial Summary of the function is to put some parameters of a function fixed (that is, set the default), return a new function, call this new function is more simple.

Notice that the new function above int2 simply base sets the parameter back to the default value 2 , but can also pass in other values when the function is called:

>>> int2 ('1000000', base=10)1000000

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

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

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

Int2 ('10010')

Equivalent:

' Base ': 2 }int ('10010', **kw)

When incoming:

Max2 = Functools.partial (max, 10)

Will actually 10 *args add the part automatically to the left, namely:

MAX2 (5, 6, 7)

Equivalent:

args = (5, 6, 7) max (*args)

The result is 10 .

Summary

When a function has too many arguments and needs to be simplified, it functools.partial can be used to create a new function that can fix some of the parameters of the original function , making it easier to invoke.

Python Learning notes (11) 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.