国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python中functools模塊函數(shù)解析

2020-02-23 04:25:29
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Python自帶的 functools 模塊提供了一些常用的高階函數(shù),也就是用于處理其它函數(shù)的特殊函數(shù)。換言之,就是能使用該模塊對(duì)可調(diào)用對(duì)象進(jìn)行處理。

functools模塊函數(shù)概覽

functools.cmp_to_key(func) functools.total_ordering(cls) functools.reduce(function, iterable[, initializer]) functools.partial(func[, args][, *keywords]) functools.update_wrapper(wrapper, wrapped[, assigned][, updated]) functools.wraps(wrapped[, assigned][, updated])

functools.cmp_to_key()

語(yǔ)法:

functools.cmp_to_key(func) 

該函數(shù)用于將舊式的比較函數(shù)轉(zhuǎn)換為關(guān)鍵字函數(shù)。

舊式的比較函數(shù):接收兩個(gè)參數(shù),返回比較的結(jié)果。返回值小于零則前者小于后者,返回值大于零則相反,返回值等于零則兩者相等。

關(guān)鍵字函數(shù):接收一個(gè)參數(shù),返回其對(duì)應(yīng)的可比較對(duì)象。例如 sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby() 都可作為關(guān)鍵字函數(shù)。

在 Python 3 中,有很多地方都不再支持舊式的比較函數(shù),此時(shí)可以使用 cmp_to_key() 進(jìn)行轉(zhuǎn)換。

示例:

sorted(iterable, key=cmp_to_key(cmp_func)) 

functools.total_ordering()

語(yǔ)法:

functools.total_ordering(cls) 

這是一個(gè)類裝飾器,用于自動(dòng)實(shí)現(xiàn)類的比較運(yùn)算。

我們只需要在類中實(shí)現(xiàn) __eq__() 方法和以下方法中的任意一個(gè) __lt__(), __le__(), __gt__(), __ge__(),那么 total_ordering() 就能自動(dòng)幫我們實(shí)現(xiàn)余下的幾種比較運(yùn)算。

示例:

@total_orderingclass Student:   def __eq__(self, other):    return ((self.lastname.lower(), self.firstname.lower()) ==        (other.lastname.lower(), other.firstname.lower()))  def __lt__(self, other):    return ((self.lastname.lower(), self.firstname.lower()) <        (other.lastname.lower(), other.firstname.lower()))

functools.reduce()

語(yǔ)法:

functools.reduce(function, iterable[, initializer]) 

該函數(shù)與 Python 內(nèi)置的 reduce() 函數(shù)相同,主要用于編寫兼容 Python 3 的代碼。

functools.partial()

語(yǔ)法:

functools.partial(func[, *args][, **keywords]) 

該函數(shù)返回一個(gè) partial 對(duì)象,調(diào)用該對(duì)象的效果相當(dāng)于調(diào)用 func 函數(shù),并傳入位置參數(shù) args 和關(guān)鍵字參數(shù) keywords 。如果調(diào)用該對(duì)象時(shí)傳入了位置參數(shù),則這些參數(shù)會(huì)被添加到 args 中。如果傳入了關(guān)鍵字參數(shù),則會(huì)被添加到 keywords 中。

partial() 函數(shù)的等價(jià)實(shí)現(xiàn)大致如下:

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            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沙坪坝区| 商南县| 成安县| 万宁市| 甘孜县| 新闻| 石柱| 海南省| 阿拉善左旗| 阿克陶县| 营山县| 龙游县| 天镇县| 益阳市| 来凤县| 云安县| 岳阳县| 资中县| 灌南县| 科技| 阿克陶县| 伊金霍洛旗| 洪洞县| 赫章县| 邹城市| 河东区| 诸暨市| 桂东县| 沈丘县| 临澧县| 新晃| 秦皇岛市| 环江| 澜沧| 望都县| 宜川县| 沙田区| 肃宁县| 祁门县| 岳阳市| 芦溪县|