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