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()))
?