今天我们要讲的偏函数,其实是函数的辅佐,什么意思呢,我们借助Python的help帮助函数,看一下
| <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/partial" title="View all posts in partial" target="_blank">partial</a></span>(func, *args, **keywords) - new function with <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/partial" title="View all posts in partial" target="_blank">partial</a></span> application | of the given arguments and keywords.
1
2
|
|
partial
(
func
,
*
args
,
*
*
keywords
)
-
new
function
with
partial
application
|
of
the
given
arguments
and
keywords
.
|
# -*- coding: utf-8 -*- """ @author:songhao @file: func.py @time: 2018/01/03 """ import <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/functools" title="View all posts in functools" target="_blank">functools</a></span> # print(dir(<span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/functools" title="View all posts in functools" target="_blank">functools</a></span>)) 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)) # /usr/local/bin/<span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/python" title="View all posts in python" target="_blank">python</a></span>3 "/Users/songhao/Desktop/<span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span> scrapy/func.py" # ['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)
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的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
冻结参数 把多个函数的部分函数进行默认赋值