文檔 地址
functools.partial
作用:
functools.partial 通過包裝手法,允許我們 "重新定義" 函數簽名
用一些默認參數包裝一個可調用對象,返回結果是可調用對象,并且可以像原始對象一樣對待
凍結部分函數位置函數或關鍵字參數,簡化函數,更少更靈活的函數參數調用
相當于 urlunquote(args, *kargs, encoding='latin1')
E.g:
def add(a, b):
return a + b
add(4, 2)
6
plus3 = functools.partial(add, 3)
plus5 = functools.partial(add, 5)
plus3(4)
7
plus3(7)
10
plus5(10)
15
應用:
典型的,函數在執行時,要帶上所有必要的參數進行調用。
然后,有時參數可以在函數被調用之前提前獲知。
這種情況下,一個函數有一個或多個參數預先就能用上,以便函數能用更少的參數進行調用。
functool.update_wrapper
默認partial對象沒有__name__和__doc__, 這種情況下,對于裝飾器函數非常難以debug.使用update_wrapper(),從原始對象拷貝或加入現有partial對象
它可以把被封裝函數的__name__、module、__doc__和 __dict__都復制到封裝函數去(模塊級別常量WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)
def wrap(func):
def call_it(*args, **kwargs):
"""wrap func: call_it"""
print 'before call'
return func(*args, **kwargs)
return call_it
@wrap
def hello():
"""say hello"""
print 'hello world'
from functools import update_wrapper
def wrap2(func):
def call_it(*args, **kwargs):
"""wrap func: call_it2"""
print 'before call'
return func(*args, **kwargs)
return update_wrapper(call_it, func)
@wrap2
def hello2():
"""test hello"""
print 'hello world2'
if __name__ == '__main__':
hello()
print hello.__name__
print hello.__doc__
print
hello2()
print hello2.__name__
print hello2.__doc__
得到結果:
before call
hello world2
hello2
test hello
functool.wraps
調用函數裝飾器partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)的簡寫
@wrap3
def hello3():
"""test hello 3"""
print 'hello world3'
functools.reduce
用這個的原因是使代碼更兼容(python3)
functools.cmp_to_key
functools.cmp_to_key(func)
將老式鼻尖函數轉換成key函數,用在接受key函數的方法中(such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby())
一個比較函數,接收兩個參數,小于,返回負數,等于,返回0,大于返回整數
key函數,接收一個參數,返回一個表明該參數在期望序列中的位置
例如:
functools.total_ordering
新聞熱點
疑難解答
圖片精選