今天我们要讲的偏函数,其实是函数的辅佐,什么意思呢,我们借助Python的help帮助函数,看一下
1 2 |
| of the given arguments and keywords. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# -*- coding: utf-8 -*- """ @author:songhao @file: func.py @time: 2018/01/03 """ import functools # print(dir(functools)) from _operator import add fc = [x for x in dir(functools) if not x.startswith('_')] print(fc) # print(help(functools.partial)) def say(name, age): return (name, age) d = functools.partial(say, age=18) print(d('songhao')) print(d('songhao',age=28)) # ['MappingProxyType', 'RLock', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', 'WeakKeyDictionary', 'cmp_to_key', 'get_cache_token', 'lru_cache', 'namedtuple', 'partial', 'partialmethod', 'recursive_repr', 'reduce', 'singledispatch', 'total_ordering', 'update_wrapper', 'wraps'] # ('songhao', 18) # ('songhao', 28) |
functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
冻结参数 把多个函数的部分函数进行默认赋值
