[英]Real world examples of partial function
One use I often put it to is printing to stderr
rather than the default stdout
. 我经常使用的一个用途是打印到stderr
而不是默认的stdout
。
from __future__ import print_function
import sys
from functools import partial
print_stderr = partial(print, file=sys.stderr)
print_stderr('Help! Little Timmy is stuck down the well!')
You can then use that with any other arguments taken by the print
function: 然后,您可以将其与print
函数采用的任何其他参数一起使用:
print_stderr('Egg', 'chips', 'beans', sep=' and ')
Another example is for, when writing Tkinter code for example, to add an identifier data to the callback function, as Tkinter callbacks are called with no parameters. 另一个例子是,当编写Tkinter代码时,例如,将标识符数据添加到回调函数,因为调用Tkinter回调没有参数。
So, suppose I want to create a numeric pad, and to know which button has been pressed: 所以,假设我想创建一个数字键盘,并知道按下了哪个按钮:
import Tkinter
from functools import partial
window = Tkinter.Tk()
contents = Tkinter.Variable(window)
display = Tkinter.Entry(window, textvariable=contents)
display.pack()
def clicked(digit):
contents.set(contents.get() + str(digit))
counter = 0
for i, number in enumerate("7894561230"):
if not i % 3:
frame = Tkinter.Frame(window)
frame.pack()
button = Tkinter.Button(frame, text=number, command=partial(clicked, number))
button.pack(side="left", fill="x")
Tkinter.mainloop()
Look at my question here: Does python have a built-in function for interleaving generators/sequences? 看看我的问题: python是否有内置函数来交错生成器/序列?
from itertools import *
from functional import *
compose_mult = partial(reduce, compose)
leaf = compose_mult((partial(imap, next), cycle, partial(imap, chain), lambda *args: args))
You will see that I have used partial application to create single-argument functions which can be passed to iterator functions (map and reduce). 您将看到我使用了部分应用程序来创建单参数函数,这些函数可以传递给迭代器函数(map和reduce)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.