Python3 Learning (18)--Partial function (Partial)

Source: Internet
Author: User

As a result of the recent business trip, there is no time is not busy, but to bother, the project is not difficult, mainly involving money in the local talk about technology slightly pale; no technology can not solve the problem, but the money is not in place, no one is willing to provide you with technology, is a stop more than a week later, spit it.

To catch up with this weekend, Ben wanted to play games, look at the American drama, take a break, but the daughter-in-law of a few soft Wen took the impetuous heart, then simply adjust, learn it, well, we will seize the time to chatter our Python, this article to understand the partial function--partial functions.


One, what is the partial function.

(1) Among the many functions of the Python functools module, one of them is the partial function, which we call the concept of a partial function module. Our next article is in detail.

(2) We've all heard of the general. In the Three Kingdoms era of the official system, the department general's assistant, and the Shang Army both for the miscellaneous general; Today we are going to talk about the partial function, in fact, is the function of adjuvant, what do you mean, we use the help of Python function, look at:



Here we mainly say the meaning of the red circle:

Partial has three parts altogether:

(1) The first part is the first parameter, which is a function, which can be defined by you, or it can be a python built-in function.

(2) The second part is a variable parameter, *args, such as the built-in function Max's parameter is a variable parameter, max (1,2,3,4,5) =5


(3) The third part is a keyword parameter, for example, the second parameter of the built-in function int is the named keyword parameter, the default base=10, which indicates that the int conversion is 10-in-system by default:




Partial function is: the function of the functions as the first parameter of the partial () function, the original function of each parameter as the partial () function of the subsequent parameters, the original function has key parameters must be taken with the keyword, there is no words, according to the original parameters in order to complement.


The text description seems a little weak, so let's start with a partial function.


second, the use of partial functions

A, the second part of the partial function (variable parameter), in order to complement the original function, the parameter will function on the original function, the last partial function returns a new function (similar to the adorner decorator, for the function of two times packaging, resulting in special effects; but unlike adorners, The partial function produces a new function, and the adorner can change the function entry address of the decorated function without affecting the original function .


Case: We define a sum function, which is *args variable, and calculates these variable parameters.

Extension: We want to sum the SUM function, plus 10 plus 20 and even more, to get a new result

Implementation: We use decorator and partial respectively to achieve, compare the difference between the two


(i) Adorner decorator implementation

We last, just learned decorator, so here, we see the demo directly, should feel very easy to get started and understand:

test.py

#/usr/bin/env Python3
#-*-encoding:utf-8-*-from

functools import wraps

def sum_add (*ARGS1): # We're going to give our decorator decorator, with the parameter
    def decorator (func):
        @wraps (func) #加上这句, the original function func be decorator function, the function of the invariant
        def My_ SUM (*ARGS2): #注意, the parameters to be consistent with the original function, the real extension is the outer adorner
            my_s = 0 for
            N in args1:
                my_s = my_s +n #这个是我们新加的求和结果
            return func (*ARGS2) + my_s #这个, we add s to the result of the original SUM function, and returns the value returned by
        #返回my_sum函数 My_sum, which extends the function of the original function.
    Decorator  #返回我们的装饰器

@sum_add (10,20) #启用装饰器 extend the sum function 
def sum (*args):
    s = 0 for
    N in args:< C18/>s = s+n return
    s
print (sum (1,2,3,4,5))
print (sum.__name__)

The return of sum (1,2,3,4,5) is by no means 15, which loses the meaning of the adorner's existence, and, of course, we know that the last value returned by sum should be 10+20+15 = 45, so that our decorator achieves the extended functionality we want, and finally, found that the original function sum's name attribute is still sum, stating that this decorative extension function does not affect our original function:



(ii) Partial function implementation of partial functions

This is the focus of our article, ready, and we'll start:

Let's take a look at the normal function, how we're going to implement

A: normal function variable parameter sequential execution

#/usr/bin/env Python3
#-*-encoding:utf-8-*-

def sum (*args):
    s = 0 for
    n in args:
        s = s + N
    ret Urn s
print (sum (10,20) +sum (1,2,3,4,5))

If we want to achieve the effect of +10+20, must write two times sum, this is clearly the most understandable, but, but it seems very sloppy unprofessional, we look at the results:



B: Ordinary function variable parameter plus keyword parameter combination

For the above a process, we changed the code to make our code look slightly complicated, but slightly professional:

#/usr/bin/env Python3
#-*-encoding:utf-8-*-

def sum (*args,**others):
    s = 0 for
    n in args:
        s = s + n
    S1 = 0 for 
    K in others:
        S1 = s1 + others[k] #我们还要算一下, the sum contained in the keyword parameter, K is the key word in Dict
    #最终, we implement the extension function, sequence parameters and keyword parameter results are added
    
d= {' value1 ': A, ' value2 ':} 
print (sum (1,2,3,4,5,**d))

The code looks professional, but feels redundant, unnecessary, and complex is not our Python style, we look at the result of B:



C: Partial function variable parameter sequential fill one-step

Above A and b we have said, both of these methods are not good, obviously, such a simple matter, we do not have to trouble decorator, then we have a solution. Yes, Python provides us with a partial function, come on, the protagonist:

Tip: Two ways to use partial function

(1) Import Functools-->functools.partial (Func,*args)
(2) from Functools Import partial-->partial (Func,*args)


We choose the second, we look at the demo:

#/usr/bin/env Python3
#-*-encoding:utf-8-*-
from  functools import partial

def sum (*args):
    s = 0< C5/>for N in args:
        s = s + N-return
    s

sum_add_10    = partial (sum,10)    #10 function at the position of sum's first parameter
sum_add_ 10_20 = partial (sum,10,20) #10 20 respectively in the position of Sum's first and second parameters
print (' a____________ we look at the function of sum of the original function address entry: ')
print (sum
print (' b______ we look at the partial function return address entry: ') print (
partial (sum,10))
print (Sum_add_10 (1,2,3,4,5))    #--> + 1 + 2 + 3 + 4 + 5 =
print (sum_add_10_20 (1,2,3,4,5)) #--> 10 + 20 + 1 + 2 + 3 + 4 + 5 = 45

Above, as you can see, we have the sum of the SUM function, plus 10, or add 10 plus 20, and even more, can be achieved by the partial function, attention to the second part of the function, the parameters are variable, is in order to go, therefore, the partial function of the new function, sum_add_10 is actually equivalent to sum (10,*args):



Through a few examples, we finally found that the partial function is more convenient, a line of code is done, and the new definition of functions, can be easily known according to the function name, the function of the expansion of the original function is which, what the effect is:





B, the third part of the partial function (keyword parameter), according to the original function of the keyword parameters to fill, the parameters will function on the original function, the last partial function return a new function

Case: We define a mod remainder function, two parameters, one is divisor, one is divisor, divisor we are here with the named keyword parameter, default value 2

Extension: Our divisor is not fixed, can be to 2 on the line for the rest, can also be 3, to 4, in short we need to specify the value of the divisor

Return result: True or False

Implementation: Realization of original function and realization of partial function

Demo as follows:

#/usr/bin/env Python3
#-*-encoding:utf-8-*-
import  functools 
def mod (m,*,key=2): return
 m% key = = 0
mod_to_2 = functools.partial (mod,key=2)
print (' a__3___ with the default keyword parameter of the original function for 2: ')
print (mod (3))                           # The remainder of 2-the original function uses the default parameter
print (' b__3___ uses a partial function to balance 2: ')
print (Mod_to_2 (3))                      #对2进行求余--The new function--the partial function produces
mod_ To_5 = functools.partial (mod,key=5) 
print (' c__25___ uses the keyword parameter of the original function to rest on 5: ')
print (mod (25,key=5))                    # The remainder of 5--the original function
print (' d__25___ uses a partial function for 5: ')
print (mod_to_5)                     #对5进行求余--The new function--the partial function

Let's look at the results:



We found that, in fact, the function of the partial function, in fact, similar to the original function, but we have to call the original function many times, some parameters, we need to manually to provide values, such as the above 5 for the remainder, if we want to know, 15,45,30 these numbers can be divisible by 5, then, We use the original function, we need to write three times, key=5, however, we use the partial function, we only need to repeatedly invoke the newly generated function mod_to_5 (or or 30), as for divisor 5, the partial function has been set for us, so:

When the number of arguments for a function is too much to simplify, use functools.partial to create a new function that can hold some of the parameters of the original function, making it simpler to invoke. Of course, decorator can also be achieved, if we are not too troublesome.


Conclusion:

If one scenario doesn't work, we'll switch to another option, and if both options work, we can make sure that the simplest and most efficient solution will be the one that ultimately benefits us.




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.