Python的functools模塊使用及說明
partial
用于創(chuàng)建一個偏函數(shù),將默認參數(shù)包裝一個可調用對象,返回結果也是可調用對象。
偏函數(shù)可以固定住原函數(shù)的部分參數(shù),從而在調用時更簡單。
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 中等同于內建函數(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 和 內建函數(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ù)轉化為 key 函數(shù)
lru_cache
允許我們將一個函數(shù)的返回值快速地緩存或取消緩存。
該裝飾器用于緩存函數(shù)的調用結果,對于需要多次調用的函數(shù),而且每次調用參數(shù)都相同,則可以用該裝飾器緩存調用結果,從而加快程序運行。
該裝飾器會將不同的調用結果緩存在內存中,因此需要注意內存占用問題。
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ù)的類型來判斷調用哪個函數(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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Python functools模塊學習總結
- Python中functools模塊的常用函數(shù)解析
- Python中functools模塊函數(shù)解析
- Python使用functools實現(xiàn)注解同步方法
- Python3標準庫之functools管理函數(shù)的工具詳解
- Python編程functools模塊創(chuàng)建修改的高階函數(shù)解析
- Python庫functools示例詳解
- Python中的functools partial詳解
- python高階函數(shù)functools模塊的具體使用
- Python中Functools模塊的高級操作詳解
- Python函數(shù)式編程模塊functools的使用與實踐

