2020年11月5日 / 366次阅读 / Last Modified 2020年11月5日
partial函数是我学习的functools模块中的第2个函数,它可以用来快速创建callable对象(可像函数一样调用的对象,包括函数)。
比如我个人的common项目中有一个函数是shex:
def shex(ch, *, prefix=True, upper=True):
"""Return the full hex representation of ch w/o 0x prefix.
ch is 0 -- 255 (Small range) in int type, since python has no char type.
The hex function in stdlib would omit the leading zero, shex would not.
"""
if ch < 0 or ch > 255:
raise ValueError('ch should be 0 -- 255.')
rt = hex(ch)[2:].upper() if upper else hex(ch)[2:]
return '0x'+rt.rjust(2,'0') if prefix else rt.rjust(2,'0')
在使用的时候,你会发现输入prefix和upper这两个参数,代码看起来就有些别扭,就是感觉输入的太多了。可我又不想直接修改shex函数,此时就可以使用partial,如下:
shex_pu = partial(shex)
shex_u = partial(shex, prefix=False)
shex_pl = partial(shex, upper=False)
shex_l = partial(shex, prefix=False, upper=False)
用函数名来区分几组不同参数的取值,你可以试一下,如果不使用partial,要定义这4个扩展函数,要写更多的代码。(shex_pu也可以直接写成 = shex,我这样写是为了pydoc好看一点)
partial的另一个应用,我个人认为,就是在需要在输入带参数的额callable对象的时候,比如iter函数,如果我们有一个函数是带参数的,想用iter来做迭代,此时就要用到partial来封装一下了:
>>> import random
>>> def test(a):
... return a + random.randint(0,9)
...
>>> from functools import partial
>>> for i in iter(partial(test,5),10):
... print(i)
...
5
7
12
12
14
9
13
7
8
12
>>>
循环调用test(5),直到返回的结果为10的时候结束,注意最后的10不输出(iter函数的sentinel参数)!
-- EOF --
本文链接:https://www.pynote.net/archives/2725
《functools.partial的使用》有2条留言
前一篇:pass和Ellipsis(...)
后一篇:profile模块的使用
©Copyright 麦新杰 Since 2019 Python笔记
stackoverflow上有人这样介绍partial:
这说明了,使用partial的时候,参数如何使用。 [ ]网上有人说partial是偏函数。 [ ]