Summary: Python's design core principle is simplicity--under the guidance of this principle, a lambda expression and a partial function are born: Both make function calls concise. This article mainly introduces you to the application of the partial function.
1. Why do I use a partial function
If we define a function, such as adding four numbers to add (one, two,three,four), there are many functions at the top that need to call this function. In these calls, 80% of the calls passed the arguments are one=1,two=20, if we enter the same parameters every time, so tedious and wasteful, of course, we can solve the problem by default parameters, but if we also need parameters is one=2,two=10 case. So, we need a function that converts any number of arguments to function objects with the remaining arguments.
2. What is a partial function
Through the above, we probably understand what is a partial function: simply, the partial function is a certain function with the implementation of fixed parameters, so we need to: 1 to the partial function named 2 to pass the fixed parameter
Look at the following example:
>>> from operator Import Add,mul
>>> from Functools Import partial
>>> add1=partial (add,1)
>>> Add (2,4)
6
>>> Add (1,2)
3
3. How to use a partial function
Perhaps you have not yet felt the power of the partial function, here is a common application scenario. In a GUI program, a control often has many parameters: size, length, maximum size, foreground color, background color, and so on, while we use the same control in large quantities, the partial function is very useful at this time. Examples and results of a GUI application are given below:
1 #!/usr/bin/python
2 from functools import partial
3 import tkinter
4 root=tkinter.tk ()
5 mybutton= Partial (tkinter.button,root,fg= ' white ', bg= ' Blue ')
6 B1=mybutton (text= ' Button1 ')
7 B2=mybutton (text= ' Button2 ')
8 Qb=mybutton (text= ' QUIT ', bg= ' red ', Command=root.quit)
9 b1.pack ()
b2.pack ()
11 Qb.pack (fill=tkinter.x,expand=true)
root.title (' paf! ')
Root.mainloop ()