functools 是python2.5被引人的,一些工具函数放在此包里。

python2.7中

python3.6中

import functools
print(dir(functools))

  

['MappingProxyType', 'RLock', 'WRAPPER_ASSIGNMENTS',
'WRAPPER_UPDATES', 'WeakKeyDictionary', '_CacheInfo',
'_HashedSeq', '__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', '_le_from_ge',
'_le_from_gt', '_le_from_lt', '_lru_cache_wrapper', '_lt_from_ge',
'_lt_from_gt', '_lt_from_le', '_make_key', 'cmp_to_key',
'get_cache_token', 'lru_cache', 'namedtuple', 'partial',
'partialmethod', 'recursive_repr', 'reduce', 'singledispatch',
'total_ordering', 'update_wrapper', 'wraps']

python3中增加了更多工具函数,做业务开发时大多情况下用不到,此处介绍使用频率较高的2个函数。

partial函数(偏函数)

把一个函数的某些参数设置默认值,返回一个新的函数,调用这个新函数会更简单。

import functools

def showarg(*args, **kw):
print(args)
print(kw) p1 = functools.partial(showarg, 1, 2, 3)
p1()
p1(4, 5, 6)
p1(a='python', b='itcast')
p2 = functools.partial(showarg, a=3, b='linux')
p2()
p2(1, 2)
p2(a='python', b='itcast') '''
(1, 2, 3)
{}
(1, 2, 3, 4, 5, 6)
{}
(1, 2, 3)
{'a': 'python', 'b': 'itcast'}
()
{'a': 3, 'b': 'linux'}
(1, 2)
{'a': 3, 'b': 'linux'}
()
{'a': 'python', 'b': 'itcast'}
'''

wraps函数

使用装饰器时,有一些细节需要被注意。例如,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)。

添加后由于函数名和函数的doc发生了改变,对测试结果有一些影响,例如:

def note(func):
"note function" def wrapper():
"wrapper function"
print('note something')
return func()
return wrapper @note
def test():
"test function"
print('I am test') test()
print(test.__doc__)
'''
note something
I am test
wrapper function '''

所以,Python的functools包中提供了一个叫wraps的装饰器来消除这样的副作用。例如:

import functools

def note(func):
"note function"
@functools.wraps(func)
def wrapper():
"wrapper function"
print('note something')
return func()
return wrapper @note
def test():
"test function"
print('I am test') test()
print(test.__doc__) '''
note something
I am test
test function
'''

  

最新文章

  1. 使用git grep进行git搜索
  2. goldengate studio 12.2.1.2.6发布
  3. Senparc.Weixin.MP SDK 微信公众平台开发教程(四):Hello World
  4. UITableview cell 的多选
  5. C# 加密解密
  6. 在Windows下安装64位压缩包版mysql 5.7.11版本的方法
  7. SQL Server 一些关键字详解(二)
  8. 踩过的坑系列之InputStream.read(byte[])方法
  9. struts2原理架构图
  10. Tomcat 启动 Debug模式
  11. jquery的ajax全局事件详解
  12. 4517: [Sdoi2016]排列计数
  13. 【Linux】常见基础命令之系统操作
  14. 游戏中Row所指代的是什么?
  15. django中form组件
  16. 二分查找(lower_bound和upper_bound)
  17. 如何移动 nuget 缓存文件夹
  18. 分享关于js解析URL中的参数的方法
  19. js函数前加分号和感叹号是什么意思?有什么用?
  20. hibernate 中 fetch=FetchType.LAZY 懒加载失败处理

热门文章

  1. Mysql导出(多张表)表结构及表数据 mysqldump用法
  2. hessian 在spring中的使用 (bean 如 Dao无法注入的问题)
  3. Python记录6:函数2,函数参数
  4. linux命令-查找所有文件中包含某个字符串
  5. BestCoder Round #55 ($)
  6. Windsor
  7. 前端和后台BUG区分方法
  8. 主流的Nosql数据库的对比
  9. loadRunner回访脚本时报Error -27987: Requested image not found [MsgId: MERR-27987]
  10. ref 参数与out参数