Python partial function

Source: Internet
Author: User

When a function has many parameters, the caller needs to provide multiple arguments. If you reduce the number of parameters, you can simplify the burden on the caller.

For example, the Int () function converts a string to an integer, and when only the string is passed in, the Int () function defaults to decimal conversion:

>>> int ('12345')12345

However, the Int () function also provides an additional base parameter with a default value of 10 for decimal. If you pass in the base parameter, you can do an N-ary conversion:

>>> Int ('12345', base=8)5349>>> int ('12345  ', 74565

Assuming that you want to convert a large number of binary strings, it is very troublesome to pass in int (x, base=2) every time, so we think that we can define a function of Int2 () and pass the base=2 in by default:

def int2 (x, base=2):    return int (x, Base)

In this way, it is very convenient for us to convert the binary:

>>> int2 ('1000000')64>>> int2 ('1010101 ' )85

Functools.partial is to help us create a biased function, we do not need to define INT2 (), you can directly use the following code to create a new function Int2:

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

So, functools.partial can turn a function with many parameters into a new function with fewer parameters, and fewer parameters need to specify a default value at the time of creation, so the difficulty of the new function call is reduced.

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