python之6-5偏函数

  • functools.partialpython

  • 偏函数的做用是简化操做,简化什么操做呢?就是当咱们有一个已知函数A,且这个函数包含有某个或多个参数A1,经过固定这个参数A1,咱们能够本身编写一个新函数B,来减小代码量,偏函数的做用就是经过偏函数调用A,固定A1,造成一个新函数函数

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

#!/usr/bin/env python

# coding=utf-8

print 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 

3

16
  • 若是使用偏函数来构造int2,那么应该是这么写:
#!/usr/bin/env python

# coding=utf-8

print int('11',base=2)

def int2(x,base=2):

    print int(x,base)

int2('10',base=16)

import functools

int3 = functools.partial(int,base=2)

print int3('10',base=16)

root@aaa103439-pc:/home/aaa103439/桌面/python# python test6_偏函数.py 

3

16

16
相关文章
相关标签/搜索