Python的functools模塊使用及說明
partial
用于創(chuàng)建一個偏函數(shù),將默認參數(shù)包裝一個可調(diào)用對象,返回結(jié)果也是可調(diào)用對象。
偏函數(shù)可以固定住原函數(shù)的部分參數(shù),從而在調(diào)用時更簡單。
from functools import partial
int2 = partial(int, base=8)
print(int2('123'))
# 83update_wrapper
使用 partial 包裝的函數(shù)是沒有__name__和__doc__屬性的。
update_wrapper 作用:將被包裝函數(shù)的__name__等屬性,拷貝到新的函數(shù)中去。
from functools import update_wrapper
def wrap2(func):
?? ?def inner(*args):
?? ??? ?return func(*args)
?? ?return update_wrapper(inner, func)
@wrap2
def demo():
?? ?print('hello world')
print(demo.__name__)
# demowraps
warps 函數(shù)是為了在裝飾器拷貝被裝飾函數(shù)的__name__。
就是在update_wrapper上進行一個包裝
from functools import wraps
def wrap1(func):
?? ?@wraps(func)?? ?# 去掉就會返回inner
?? ?def inner(*args):
?? ??? ?print(func.__name__)
?? ??? ?return func(*args)
?? ?return inner
@wrap1
def demo():
?? ?print('hello world')
print(demo.__name__)
# demoreduce
在 Python2 中等同于內(nèi)建函數(shù) reduce
函數(shù)的作用是將一個序列歸納為一個輸出
reduce(function, sequence, startValue) from functools import reduce l = range(1,50) print(reduce(lambda x,y:x+y, l)) # 1225
cmp_to_key
在 list.sort 和 內(nèi)建函數(shù) sorted 中都有一個 key 參數(shù)
x = ['hello','worl','ni'] x.sort(key=len) print(x) # ['ni', 'worl', 'hello']
Python3 之前還提供了cmp參數(shù)來比較兩個元素
cmp_to_key 函數(shù)就是用來將老式的比較函數(shù)轉(zhuǎn)化為 key 函數(shù)
lru_cache
允許我們將一個函數(shù)的返回值快速地緩存或取消緩存。
該裝飾器用于緩存函數(shù)的調(diào)用結(jié)果,對于需要多次調(diào)用的函數(shù),而且每次調(diào)用參數(shù)都相同,則可以用該裝飾器緩存調(diào)用結(jié)果,從而加快程序運行。
該裝飾器會將不同的調(diào)用結(jié)果緩存在內(nèi)存中,因此需要注意內(nèi)存占用問題。
from functools import lru_cache @lru_cache(maxsize=30) ?# maxsize參數(shù)告訴lru_cache緩存最近多少個返回值 def fib(n): ? ? if n < 2: ? ? ? ? return n ? ? return fib(n-1) + fib(n-2) print([fib(n) for n in range(10)]) fib.cache_clear() ? # 清空緩存
singledispatch
單分發(fā)器, Python3.4新增,用于實現(xiàn)泛型函數(shù)。
根據(jù)單一參數(shù)的類型來判斷調(diào)用哪個函數(shù)。
from functools import singledispatch
@singledispatch
def fun(text):
?? ?print('String:' + text)
@fun.register(int)
def _(text):
?? ?print(text)
@fun.register(list)
def _(text):
?? ?for k, v in enumerate(text):
?? ??? ?print(k, v)
@fun.register(float)
@fun.register(tuple)
def _(text):
?? ?print('float, tuple')
fun('i am is hubo')
fun(123)
fun(['a','b','c'])
fun(1.23)
print(fun.registry)?? ?# 所有的泛型函數(shù)
print(fun.registry[int])?? ?# 獲取int的泛型函數(shù)
# String:i am is hubo
# 123
# 0 a
# 1 b
# 2 c
# float, tuple
# {<class 'object'>: <function fun at 0x106d10f28>, <class 'int'>: <function _ at 0x106f0b9d8>, <class 'list'>: <function _ at 0x106f0ba60>, <class 'tuple'>: <function _ at 0x106f0bb70>, <class 'float'>: <function _ at 0x106f0bb70>}
# <function _ at 0x106f0b9d8>以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信