Python之partial函数

介绍

partial其实是Python模块functools中定义的一个函数,当我们需要经常调用某个函数时,但是其中某些参数是已知的固定值,这样可能会让代码显得冗余,这个时候就可以考虑使用partial函数。

使用

假设我们要做二进制转十进制

int('1000000', base=2)
# 64
int('1010101', base=2)
# 85

如果我们要重复使用这个函数,需要重复写的东西就会很多
但是如果我们使用partial

from functools import partial
int2 = partial(int, base=2)

int2('110')
# 6

猜你喜欢

转载自www.cnblogs.com/mrdoghead/p/12019927.html