functools 模塊詳解

functool.reduce 方法是迭代的應(yīng)用傳入的方法用前面得到的值來作為輸入,所以方法最好有兩個(gè)以上的變量,不然就不能迭代了

import functools
def ad(x,y):
    return x*y
?
functools.reduce(ad,[2,3,4])
24

functools.partial 函數(shù)可以為函數(shù)提供定義好的輸入變量,就像是函數(shù)的預(yù)定義變量一樣,

In [27]:

def hello(one,two,three):
    if one:
        return two
    else:
        return three
    
par_func = functools.partial(hello,two='yes',three='no')
par_func(1)
Out[27]:
'yes'

functools.wraps 用這個(gè)函數(shù)定義函數(shù)的包裝器,

In [33]:

from functools import wraps 
def my_decorator(f):
    @wraps(f)
    def wraper(*args,**kwds):
        print('calling decorators now')
        return f(*args,**kwds)
    return wraper
?
@my_decorator
def use_decorator():
    print('function use decotator')
    
use_decorator()
    
calling decorators now
function use decorator

functools.total_ordering 定義類的比較方式

In [35]:

from functools import total_ordering
@total_ordering
class 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()))
?
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容