partial :
你可以使用partial函数(其实是个class)从原函数中派生出固定某些参数的新函数,使函数所需的参数减少(因为相当于设定好了某些参数的值),从而简化代码.
partial的定义代码片段:
class partial:
"""New function with partial application of the given arguments
and keywords.
"""
__slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
def __new__(*args, **keywords):
if not args:
raise TypeError("descriptor '__new__' of partial needs an argument")
if len(args) < 2:
raise TypeError("type 'partial' takes at least one argument")
cls, func, *args = args
if not callable(func):
raise TypeError("the first argument must be callable")
args = tuple(args)
if hasattr(func, "func"):
args = func.args + args
tmpkw = func.keywords.copy()
tmpkw.update(keywords)
keywords = tmpkw
del tmpkw
func = func.func
self = super(partial, cls).__new__(cls)
self.func = func
self.args = args
self.keywords = keywords
return self
def __call__(*args, **keywords):
if not args:
raise TypeError("descriptor '__call__' of partial needs an argument")
self, *args = args
newkeywords = self.keywords.copy()
newkeywords.update(keywords)
return self.func(*self.args, *args, **newkeywords)
...
例子:
from functools import partial
def multimath(a,b,mode):
if mode == "add":
return a+b
elif mode =="multi":
return a*b
elif mode =="sub":
return a-b
elif mode == "divide":
return a/b
multimath = partial(multimath,mode ="multi")
print(multimath(3,4))
multimath = partial(multimath,4,mode ="divide")
print(multimath(3))
outcome:
12
1.3333333333333333
思考:
- partial() 可以给输入函数指定默认参数,简化之后的函数参数量
- partial() 既可以设定args 参数,又可以设定关键词参数
.当设定args参数时,输入的数值将会按照待处理函数中args参数的顺序依次指定.如**kwargs
中4作为partial(multimath,4,mode ="divide")
中第一个参数a来被指定,这样转化后的multimath
默认首先输入了参数4,然后才输入第二个参数3(也就是b的值)multimath