在python中,如果在设置某个函数的时候需要把函数的某个参数设置为固定的值,就可以使用偏函数来实现
偏函数实现方法
functools 其中就包含偏函数(partial)
| 方法一 | import functools |
|---|---|
| 方法二 | from functools import partial(只导入了偏函数的库) |
partial(函数名称,参数=固定值)
如果不熟悉可用dir查看方法
dir(functools) ['GenericAlias', 'RLock', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATeS', '_CacheInfo', '_HashedSeq', '_NOT_FOUND', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_c3_merge', '_c3_mro', '_compose_mro', '_convert', '_find_impl', '_ge_from_gt', '_ge_from_le', '_ge_from_lt', '_gt_from_ge', '_gt_from_le', '_gt_from_lt', '_initial_missing', '_le_from_ge', '_le_from_gt', '_le_from_lt', '_lru_cache_wrapper', '_lt_from_ge', '_lt_from_gt', '_lt_from_le', '_make_key', '_unwrap_partial', 'cache', 'cached_property', 'cmp_to_key', 'get_cache_token', 'lru_cache', 'namedtuple', 'partial', 'partialmethod', 'recursive_repr', 'reduce', 'singledispatch', 'singledispatchmethod', 'total_ordering', 'update_wrapper', 'wraps']
下面举例说说明:
在实际使用前我们不妨先看一下help(int)
>>> help(int) Help on class int in module builtins: class int(object) | int([x]) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point .............
我们这里只看这里“ | int(x, base=10) -> integer”
大致意思就是把从形参进入的x当成十进制数弄成整型
#所以
int("1234",base=10)
#结果为1234
int("1234",base=8)
#结果为668
int("1234",base=16)
#结果为4660
好的理解int用法后我们实际看一下parttial
>>> import functools
>>> int3=functools.partial(int,base=2)
>>> int3("1101")
13
>>> int3("11101")
29



