Python庫functools示例詳解
functools模塊是Python的標準庫的一部分,它是為高階函數(shù)而實現(xiàn)的。高階函數(shù)是作用于或返回另一個函數(shù)或多個函數(shù)的函數(shù)。一般來說,對這個模塊而言,任何可調(diào)用的對象都可以作為一個函數(shù)來處理。
functools 提供了 11個函數(shù):
1. cached_property
將類的方法轉(zhuǎn)換為一個屬性,該屬性的值計算一次,然后在實例的生命周期中將其緩存作為普通屬性。與 property() 類似,但添加了緩存,對于在其他情況下實際不可變的高計算資源消耗的實例特征屬性來說該函數(shù)非常有用。
# cached_property 緩存屬性
class cached_property(object):
"""
Decorator that converts a method with a single self argument into a
property cached on the instance.
Optional ``name`` argument allows you to make cached properties of other
methods. (e.g. url = cached_property(get_absolute_url, name='url') )
"""
def __init__(self, func, name=None):
# print(f'f: {id(func)}')
self.func = func
self.__doc__ = getattr(func, '__doc__')
self.name = name or func.__name__
def __get__(self, instance, type=None):
# print(f'self func: {id(self.func)}')
# print(f'instance: {id(instance)}')
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
return res
class F00():
@cached_property
def test(self):
# cached_property 將會把每個實例的屬性存儲到實例的__dict__中, 實例獲取屬性時, 將會優(yōu)先從__dict__中獲取,則不會再次調(diào)用方法內(nèi)部的過程
print(f'運行test方法內(nèi)部過程')
return 3
@property
def t(self):
print('運行t方法內(nèi)部過程')
return 44
f = F00()
print(f.test) # 第一次將會調(diào)用test方法內(nèi)部過程
print(f.test) # 再次調(diào)用將直接從實例中的__dict__中直接獲取,不會再次調(diào)用方法內(nèi)部過程
print(f.t) # 調(diào)用方法內(nèi)部過程取值
print(f.t) # 調(diào)用方法內(nèi)部過程取值
# 結(jié)果輸出
# 運行test方法內(nèi)部過程
# 3
# 3
# 運行t方法內(nèi)部過程
# 44
# 運行t方法內(nèi)部過程
# 44
2. cmp_to_key
在 list.sort 和 內(nèi)建函數(shù) sorted 中都有一個 key 參數(shù)
x = ['hello','worl','ni'] x.sort(key=len) print(x) # ['ni', 'worl', 'hello']
3. 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() # 清空緩存4. 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'))
# 835. partialmethod
對于python 偏函數(shù)partial理解運用起來比較簡單,就是對原函數(shù)某些參數(shù)設(shè)置默認值,生成一個新函數(shù)。而如果對于類方法,因為第一個參數(shù)是 self,使用 partial 就會報錯了。
class functools.partialmethod(func, /, *args, **keywords) 返回一個新的 partialmethod 描述器,其行為類似 partial 但它被設(shè)計用作方法定義而非直接用作可調(diào)用對象。
func 必須是一個 descriptor 或可調(diào)用對象(同屬兩者的對象例如普通函數(shù)會被當作描述器來處理)。
當 func 是一個描述器(例如普通 Python 函數(shù), classmethod(), staticmethod(), abstractmethod() 或其他 partialmethod 的實例)時, 對 __get__ 的調(diào)用會被委托給底層的描述器,并會返回一個適當?shù)?部分對象 作為結(jié)果。
當 func 是一個非描述器類可調(diào)用對象時,則會動態(tài)創(chuàng)建一個適當?shù)慕壎ǚ椒ā?當用作方法時其行為類似普通 Python 函數(shù):將會插入 self 參數(shù)作為第一個位置參數(shù),其位置甚至會處于提供給 partialmethod 構(gòu)造器的 args 和 keywords 之前。
from functools import partialmethod
class Cell:
def __init__(self):
self._alive = False
@property
def alive(self):
return self._alive
def set_state(self, state):
self._alive = bool(state)
set_alive = partialmethod(set_state, True)
set_dead = partialmethod(set_state, False)
print(type(partialmethod(set_state, False)))
# <class 'functools.partialmethod'>
c = Cell()
c.alive
# False
c.set_alive()
c.alive
# True6. reduce
函數(shù)的作用是將一個序列歸納為一個輸出reduce(function, sequence, startValue)
from functools import reduce l = range(1,50) print(reduce(lambda x,y:x+y, l)) # 1225
7. singledispatch
單分發(fā)器,用于實現(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>
8. singledispatchmethod
與泛型函數(shù)類似,可以編寫一個使用不同類型的參數(shù)調(diào)用的泛型方法聲明,根據(jù)傳遞給通用方法的參數(shù)的類型,編譯器會適當?shù)靥幚砻總€方法調(diào)用。
class Negator:
@singledispatchmethod
def neg(self, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(self, arg: int):
return -arg
@neg.register
def _(self, arg: bool):
return not arg9. total_ordering
它是針對某個類如果定義了lt、le、gt、ge這些方法中的至少一個,使用該裝飾器,則會自動的把其他幾個比較函數(shù)也實現(xiàn)在該類中
from functools import total_ordering
class Person:
# 定義相等的比較函數(shù)
def __eq__(self,other):
return ((self.lastname.lower(),self.firstname.lower()) ==
(other.lastname.lower(),other.firstname.lower()))
# 定義小于的比較函數(shù)
def __lt__(self,other):
return ((self.lastname.lower(),self.firstname.lower()) <
(other.lastname.lower(),other.firstname.lower()))
p1 = Person()
p2 = Person()
p1.lastname = "123"
p1.firstname = "000"
p2.lastname = "1231"
p2.firstname = "000"
print p1 < p2 # True
print p1 <= p2 # True
print p1 == p2 # False
print p1 > p2 # False
print p1 >= p2 # False10. update_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__)
# demo11. wraps
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__)
# demo參考文獻
到此這篇關(guān)于Python庫functools詳解的文章就介紹到這了,更多相關(guān)Python庫functools內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python functools模塊學習總結(jié)
- 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的使用與實踐
相關(guān)文章
全網(wǎng)最新用python實現(xiàn)各種文件類型轉(zhuǎn)換的方法
這篇文章主要介紹了用python實現(xiàn)各種文件類型轉(zhuǎn)換的方法,包括word轉(zhuǎn)pdf,excel轉(zhuǎn)pdf,ppt轉(zhuǎn)pdf,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2023-05-05
Python調(diào)用百度AI實現(xiàn)顏值評分功能
這篇文章主要介紹了應(yīng)用百度AI的人臉識別功能對年齡、性別、顏值等進行識別,代碼具有一定的學習價值,感興趣的朋友跟隨小編一起看看吧2021-11-11

