日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python的functools模塊使用及說明_python

作者:Python之簡 ? 更新時間: 2022-09-06 編程語言

partial

用于創建一個偏函數,將默認參數包裝一個可調用對象,返回結果也是可調用對象。

偏函數可以固定住原函數的部分參數,從而在調用時更簡單。

from functools import partial

int2 = partial(int, base=8)
print(int2('123'))
# 83

update_wrapper

使用 partial 包裝的函數是沒有__name__和__doc__屬性的。

update_wrapper 作用:將被包裝函數的__name__等屬性,拷貝到新的函數中去。

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__)
# demo

wraps

warps 函數是為了在裝飾器拷貝被裝飾函數的__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__)
# demo

reduce

在 Python2 中等同于內建函數 reduce

函數的作用是將一個序列歸納為一個輸出

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 和 內建函數 sorted 中都有一個 key 參數

x = ['hello','worl','ni']
x.sort(key=len)
print(x)
# ['ni', 'worl', 'hello']

Python3 之前還提供了cmp參數來比較兩個元素

cmp_to_key 函數就是用來將老式的比較函數轉化為 key 函數

lru_cache

允許我們將一個函數的返回值快速地緩存或取消緩存。

該裝飾器用于緩存函數的調用結果,對于需要多次調用的函數,而且每次調用參數都相同,則可以用該裝飾器緩存調用結果,從而加快程序運行。

該裝飾器會將不同的調用結果緩存在內存中,因此需要注意內存占用問題。

from functools import lru_cache
@lru_cache(maxsize=30) ?# maxsize參數告訴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

單分發器, Python3.4新增,用于實現泛型函數。

根據單一參數的類型來判斷調用哪個函數。

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)?? ?# 所有的泛型函數
print(fun.registry[int])?? ?# 獲取int的泛型函數
# 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>

原文鏈接:https://blog.csdn.net/qq_1290259791/article/details/84930850

欄目分類
最近更新