python之6-5偏函数,,functools.


functools.partial

偏函数的作用是简化操作,简化什么操作呢?就是当我们有一个已知函数A,且这个函数包含有某个或多个参数A1,通过固定这个参数A1,我们可以自己编写一个新函数B,来减少代码量,偏函数的作用就是通过偏函数调用A,固定A1,形成一个新函数

比如int()函数,这个函数将任何进制转换为十进制,参数是base,正常调用的代码如下:

#!/usr/bin/env python# coding=utf-8print int(‘11‘,base=2)def int2(x,base=2):    print int(x,base)int2(‘10‘,16)
root@aaa103439-pc:/home/aaa103439/桌面/python# python test6_偏函数.py 316
如果使用偏函数来构造int2,那么应该是这么写:
#!/usr/bin/env python# coding=utf-8print int(‘11‘,base=2)def int2(x,base=2):    print int(x,base)int2(‘10‘,base=16)import functoolsint3 = functools.partial(int,base=2)print int3(‘10‘,base=16)
root@aaa103439-pc:/home/aaa103439/桌面/python# python test6_偏函数.py 31616

python之6-5偏函数,布布扣,bubuko.com

python之6-5偏函数

评论关闭