Example Analysis of partial function partial usage in python, pythonpartial

Source: Internet
Author: User

Example Analysis of partial function partial usage in python, pythonpartial

This example describes the usage of partial function partial in python. Share it with you for your reference. The details are as follows:

When a function is executed, all necessary parameters must be included for calling. However, sometimes the parameters can be known in advance before the function is called. In this case, one or more parameters of a function can be used in advance, so that the function can be called with fewer parameters.

For example:

In [9]: from functools import partialIn [10]: def add(a,b):....: return a+b....:In [11]: add(4,3)Out[11]: 7In [12]: plus = partial(add,100)In [13]: plus(9)Out[13]: 109In [14]: plus2 = partial(add,99)In [15]: plus2(9)Out[15]: 108

Actually, when a function is called, there are multiple parameter parameters, but one of them is known. We can use this parameter to re-bind a new function, then call the new function.

If there are default parameters, they can also be automatically matched, for example:

In [17]: def add2(a,b,c=2):....: return a+b+c....:In [18]: plus3 = partail(add,101)---------------------------------------------------------------------------NameError Traceback (most recent call last)/Users/yupeng/Documents/PhantomJS/<ipython-input-18-d4b7c6a6855d> in <module>()----> 1 plus3 = partail(add,101)NameError: name 'partail' is not definedIn [19]: plus3 = partial(add,101)In [20]: plus3(1)Out[20]: 102In [21]: plus3 = partial(add2,101)In [22]: plus3 = partial(add2,101) (1)Out[22]: 104In [23]: plus3(1)Out[23]: 104In [24]: plus3(1,2)Out[24]: 104In [25]: plus3(1,3)Out[25]: 105In [26]: plus3(1,30)Out[26]: 132

I hope this article will help you with Python programming.

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.