python高階函數(shù)functools模塊的具體使用
functools模塊提供了一些常用的高階函數(shù)(處理其他可調(diào)用對象/函數(shù)的特殊函數(shù);以函數(shù)作為輸入?yún)?shù),返回也是函數(shù))。
functools模塊
functools模塊中的高階函數(shù)可基于已有函數(shù)定義新的函數(shù):
- cmp_to_key,
- total_ordering,
- reduce,
- partial,
- update_wrapper
- wraps
reduce
reduce(function, iterable[, initializer])對一個可迭代數(shù)據(jù)集合中的所有數(shù)據(jù)進行累積。
- function:接受兩個參數(shù)的函數(shù);
- sequence:可迭代對象(tuple/list/dict/str);
- initial:可選初始值;
# 累加 reduce(lambda x,y:x+y, [1,2,3,4]) # 10 # 逆序字符串 reduce(lambda x,y:y+x, 'abcdefg') # 'gfedcba'
partial/partialmethod
partial用于"凍結"函數(shù)的部分參數(shù),返回一個參數(shù)更少、使用更簡單的函數(shù)對象。使用時,只需傳入未凍結的參數(shù)即可。partialmethod用于處理類方法。
functools.partial(func[, *args][, **keywords])返回一個新的partial對象:
- func:一個可調(diào)用的對象或函數(shù);
- args:要凍結的位置參數(shù);
- keywords:要凍結的關鍵字參數(shù)。
def add(a, b, note="add"):
? ? result = a + b
? ? print(f"{note} result: {result}")
? ? return result
add3 = functools.partial(add, 3)
add5 = functools.partial(add, 5, note="partialed")
print(add3(1)) # add result: 4
print(add3(2, note="partial3")) # partial3 result: 5
print(add5(3)) # partialed result: 8partialmethod用于類中的方法
class Cell(object): ? ? def __init__(self): ? ? ? ? self._alive = False ? ? @property ? ? def alive(self): ? ? ? ? return self._alive ? ? def set_state(self, state): ? ? ? ? self._alive = bool(state) ? ? set_alive = functools.partialmethod(set_state, True) ? ? set_dead = functools.partialmethod(set_state, False) c = Cell() print(c.alive) ?# False c.set_alive() print(c.alive) ?# True
wraps/update_wrapper
functools.update_wrapper(wrapper, wrapped [, assigned] [, updated])更新一個包裹(wrapper)函數(shù),使其看起來更像被包裹(wrapped)的函數(shù)(即把 被封裝函數(shù)的__name__、__module__、__doc__和 __dict__都復制到封裝函數(shù)去。wraps是通過partial與update_wrapper實現(xiàn)的。
通常,經(jīng)由被裝飾(decorator)的函數(shù)會表現(xiàn)為另外一個函數(shù)了(函數(shù)名、說明等都變?yōu)榱搜b飾器的);通過wraps函數(shù)可以消除裝飾器的這些副作用。
def wrapper_decorator(func):
? ? @functools.wraps(func) # 若是去掉此wraps,則被裝飾的函數(shù)名稱與說明都變?yōu)榇撕瘮?shù)的
? ? def wrapper(*args, **kwargs):
? ? ? ? """doc of decorator"""
? ? ? ? print('in wrapper_decorator...')
? ? ? ? return func(*args, **kwargs)
? ? return wrapper
@wrapper_decorator
def example():
? ? """doc of example"""
? ? print('in example function')
example()
# in wrapper_decorator...
# in example function
print(example.__name__, "; ", example.__doc__) # example ; ?doc of examplesingledispatch/singledispatchmethod
singledispatch將普通函數(shù)轉換為泛型函數(shù),而singledispatchmethod(3.8引入)將類方法轉換為泛型函數(shù):
- 泛型函數(shù):是指由多個函數(shù)(針對不同類型的實現(xiàn))組成的函數(shù),調(diào)用時由分派算法決定使用哪個實現(xiàn);
- Single dispatch:一種泛型函數(shù)分派形式,基于第一個參數(shù)的類型來決定;
dispatch使用:
- singledispatch裝飾dispatch的基函數(shù)base_fun(即,注冊object類型);
- 注冊后續(xù)分發(fā)函數(shù)使用裝飾器@{base_fun}.register({type}),注冊每種需要特殊處理的類型;
- 分發(fā)函數(shù)名稱無關緊要,_是個不錯的選擇;
- 可以疊放多個register裝飾器,讓同一個函數(shù)支持多種類型;
# 缺省匹配類型,注冊object類型(與后續(xù)注冊類型都不匹配時使用)
@functools.singledispatch
def show_dispatch(obj):
? ? print(obj, type(obj), "dispatcher")
# 匹配str字符串
@show_dispatch.register(str)
def _(text):
? ? print(text, type(text), "str")
# 匹配int
@show_dispatch.register(int)
def _(n):
? ? print(n, type(n), "int")
# 匹配元祖或者字典
@show_dispatch.register(tuple)
@show_dispatch.register(dict)
def _(tup_dic):
? ? print(tup_dic, type(tup_dic), "tuple/dict")
### 打印注冊的類型:
# dict_keys([<class 'object'>, <class 'str'>, <class 'int'>, <class 'dict'>, <class 'tuple'>])
print(show_dispatch.registry.keys())
show_dispatch(1)
show_dispatch("xx")
show_dispatch([1])
show_dispatch((1, 2, 3))
show_dispatch({"a": "b"})
# 1 <class 'int'> int
# xx <class 'str'> str
# [1] <class 'list'> dispatcher
# (1, 2, 3) <class 'tuple'> tuple/dict
# {'a': 'b'} <class 'dict'> tuple/dictcmp_to_key
cmp_to_key()用來自定義排序規(guī)則,可將比較函數(shù)(comparison function)轉化為關鍵字函數(shù)(key function):
- 比較函數(shù):接受兩個參數(shù),比較這兩個參數(shù),并返回0、1或-1;
- 關鍵字函數(shù):接受一個參數(shù),返回其對應的可比較對象;
test = [1, 3, 5, 2, 4] test.sort(key=functools.cmp_to_key(lambda x, y: 1 if x < y else -1)) print(test) # [5, 4, 3, 2, 1]
total_ordering
是一個類裝飾器,用于自動實現(xiàn)類的比較運算;類定義一個或者多個比較排序方法,類裝飾器將會補充其余的比較方法。
被修飾的類必須至少定義 __lt__(), __le__(),__gt__(),__ge__()中的一個,以及__eq__()方法。
如,只需定義lt與eq方法,即可實現(xiàn)所有比較:
@functools.total_ordering
class Person:
? ? def __init__(self, name, age):
? ? ? ? self.name = name
? ? ? ? self.age = age
? ? def __lt__(self, other):
? ? ? ? if isinstance(other, Person):
? ? ? ? ? ? return self.age < other.age
? ? ? ? else:
? ? ? ? ? ? raise AttributeError("Incorrect attribute!")
? ? def __eq__(self, other):
? ? ? ? if isinstance(other, Person):
? ? ? ? ? ? return self.age == other.age
? ? ? ? else:
? ? ? ? ? ? raise AttributeError("Incorrect attribute!")
mike = Person("mike", 20)
tom = Person("tom", 10)
print(mike < tom)
print(mike <= tom)
print(mike > tom)
print(mike >= tom)
print(mike == tom)到此這篇關于python高階函數(shù)functools模塊的具體使用的文章就介紹到這了,更多相關python functools模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python functools模塊學習總結
- Python中functools模塊的常用函數(shù)解析
- Python中functools模塊函數(shù)解析
- Python使用functools實現(xiàn)注解同步方法
- Python3標準庫之functools管理函數(shù)的工具詳解
- Python編程functools模塊創(chuàng)建修改的高階函數(shù)解析
- Python的functools模塊使用及說明
- Python庫functools示例詳解
- Python中的functools partial詳解
- Python中Functools模塊的高級操作詳解
- Python函數(shù)式編程模塊functools的使用與實踐
相關文章
python定時檢查啟動某個exe程序適合檢測exe是否掛了
定時檢查啟動某個exe程序這種情況下適合檢測某個exe程序是否掛了,感興趣的朋友可以了解下,希望本文對你有所幫助2013-01-01
python操作excel之openpyxl模塊讀寫xlsx格式使用方法詳解
這篇文章主要介紹了python操作excel之openpyxl模塊讀寫xlsx格式使用方法詳解,需要的朋友可以參考下2022-12-12
Python中動態(tài)檢測編碼chardet的使用教程
最近利用python抓取一些網(wǎng)上的數(shù)據(jù),遇到了編碼的問題。非常頭痛,幸運的是找到了解決的方法,下面這篇文章主要跟大家介紹了關于Python中動態(tài)檢測編碼chardet的使用方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07
Python實戰(zhàn)項目用PyQt5制作漫畫臉GUI界面
PyQt5 是用來創(chuàng)建Python GUI應用程序的工具包。作為一個跨平臺的工具包,PyQt可以在所有主流操作系統(tǒng)上運行,本文主要介紹了如何用PyQt5制作漫畫臉的GUI界面2021-10-10

