1 简介
偏函数在Python 2.5 版本中添加进来,是函数式编程一系列重要改进中的一部分。使用偏函数,可以通过有效地“冻结”那些预先确定的参数来缓存函数参数,然后在运行时,当获得需要的剩余参数后,可以将它们解冻,传递到最终的参数中,从而使用最终确定的所有参数去调用函数。
偏函数最好的一点是它不只局限于函数。偏函数可以用于可调用对象(任何包括函数接口的对象),只需要通过使用圆括号即可,包括类、方法或可调用实例。对于有很多可调用对象,并且许多调用都反复使用相同参数的情况,使用偏函数会非常合适。
# 2 路牌提示实例
我们要做以下路牌:
![Paste_Image.png](https://img.haomeiwen.com/i4225992/684ffb0d675d1d41.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
点击每一个按钮会有相应的提示信息,每一个按钮形式上基本相同,可以考虑用偏函数,而不用去单独实现每一个按钮。
以下是代码:
!/usr/bin/env python
coding=utf-8
import pdb
from functools import partial as pto
from Tkinter import Tk, Button, X
from tkMessageBox import showinfo, showwarning, showerror
WARN = 'warn'
CRIT = 'crit'
REGU = 'regu'
SIGNS = {
'do not enter': CRIT,
'railroad crossing': WARN,
'55\nspeed limit': REGU,
'wrong way':CRIT,
'merging traffic':WARN,
'one way': REGU,
}
critCB = lambda: showerror('Error','Error Button Pressed!')
warnCB = lambda: showwarning('warning','Warning Button Pressed!')
infoCB = lambda: showinfo('Info','Info Button Pressed')
top = Tk()
top.title('Road Signs')
Button(top, text='QUIT',command=top.quit,bg='red',fg='white').pack()
MyButton = pto(Button,top)
CritButton = pto(MyButton, command=critCB, bg='white',fg='red')
WarnButton = pto(MyButton, command=warnCB, bg='goldenrod1')
ReguButton = pto(MyButton, command=infoCB, bg='white')
for eachSign in SIGNS:
pdb.set_trace()
signType = SIGNS[eachSign]
cmd = '%sButton(text=%r%s).pack(fill=X,expand=True)'%
(signType.title(),eachSign,'.upper()' if signType==CRIT else '.title()')
eval(cmd)
top.mainloop()
## 2.1 搞清楚`title()`,`upper()`函数的作用
![Paste_Image.png](https://img.haomeiwen.com/i4225992/362c0238f1b23866.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
>str.title()
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
`>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
`
## 2.2 三元组选择功能以及`%r`和`%s`的区别
![Paste_Image.png](https://img.haomeiwen.com/i4225992/aa9cc404c42f25d4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
注意其中`%r`的使用,如果换成`%s`会出错:
![Paste_Image.png](https://img.haomeiwen.com/i4225992/4a6eac316e84bc2b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
同时,可以看到`text=%r%s`的值为`eachSign.upper()`或者`eachSign.title()`,由`signType`是否为`CRIT`决定。
# 3 运行结果
注意不同类别的按钮,显示的界面不太相同,字体是否全为大写也不一样。这都是偏函数的应用。
![Paste_Image.png](https://img.haomeiwen.com/i4225992/684ffb0d675d1d41.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
网友评论