栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python篇 偏函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python篇 偏函数

偏函数概念

在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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498708.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号