functools.partial:
# args/keywords 调用partial的参数
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords) # 将两个字典合并
return func(*(args+fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
urlunquote = fuctool.partial(urlunquote, encoding='latin1')
这里encoding=‘latin'是keywords的参数,等同于{encoding:"latin1"}
当调用urlunquote(args, *kargs)的时候,相当于调用urlunquote(args, *kargs, encoding="latin1")
def add(a,b):
return a+b
plus3 = functools.partial(add, 3)
这里是添加了 args,也就是3这个参数到 add的fargs, 即a, b这里。这里plus3相当于调用了add(3,b),plus3(4)返回7
# 在partial里面添加*args时候,每次都会把参数自动添加到左边
max2 = functools.partial(max, 10)
max2(5,6,7)
相当于 args = (10,5,6,7)
max(*args) # 10
参考文献:
http://www.wklken.me/posts/2013/08/18/python-extra-functools.html
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819893624a7edc0e3e3df4d5d852a352b037c93ec000