部分功能的真实世界的例子

sar*_*rat 3 python lambda functional-programming function currying

我一直在经历Python的部分功能.我发现它很有趣,但如果我能用一些真实世界的例子来理解它,而不是将它理解为另一种语言特征,那将会很有帮助.

Fat*_*man 11

我经常使用的一个用途是打印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!')
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其与print函数采用的任何其他参数一起使用:

print_stderr('Egg', 'chips', 'beans', sep=' and ')
Run Code Online (Sandbox Code Playgroud)


jsb*_*eno 6

另一个例子是,当编写Tkinter代码时,例如,将标识符数据添加到回调函数,因为调用Tkinter回调没有参数.

所以,假设我想创建一个数字键盘,并知道按下了哪个按钮:

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()
Run Code Online (Sandbox Code Playgroud)

  • +1 对于其他 GUI 库(如 PyQt、wx)也很方便。 (2认同)