Python的functools
模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。通过设定参数的默认值,可以降低函数调用的难度。
code example
>>> from functools import partial
>>> int('123',base=8)
83
>>> int2 = partial(int, base=8) # int是一个函数
>>> int2('123')
83
我们使用偏函数定义了一个新函数int2
,这时我们再调用时就不用写base
这个默认参数了。
当反复调用包含大量参数的函数时,使用偏函数是一个非常好的选择。尤其是写GUI时。
看一个代码片
MyButton = partial(Tkinter.Button, root, fg='white', bg='blue')
b1 = MyButton(text='Button 1')
b2 = MyButton(text='Button 2')
是不是简化了一些呢?