這篇文章主要介紹“Python裝飾器功能介紹”,在日常操作中,相信很多人在Python裝飾器功能介紹問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Python裝飾器功能介紹”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
示例:尋找寶藏。在一個(gè)嵌套元組tuple或列表list中尋找元素'Gold Coin'
import time from functools import lru_cache def find_treasure(box): for item in box: if isinstance(item, (tuple, list)): find_treasure(item) elif item == 'Gold Coin': print('Find the treasure!') return True start = time.perf_counter() find_treasure(('sth', 'sth', 'sth', ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), 'Gold Coin', )) end = time.perf_counter() run_time_without_cache = end - start print('在沒有Cache的情況下,運(yùn)行花費(fèi)了{(lán)} s。'.format(run_time_without_cache)) @lru_cache() def find_treasure_quickly(box): for item in box: if isinstance(item, (tuple, list)): find_treasure(item) elif item == 'Gold Coin': print('Find the treasure!') return True start = time.perf_counter() find_treasure_quickly(('sth', 'sth', 'sth', ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), 'Gold Coin', )) end = time.perf_counter() run_time_with_cache = end - start print('在有Cache的情況下,運(yùn)行花費(fèi)了{(lán)} s。'.format(run_time_with_cache)) print('有Cache比沒Cache快{} s。'.format(float(run_time_without_cache-run_time_with_cache)))
最終輸出
Find the treasure!
在沒有Cache的情況下,運(yùn)行花費(fèi)了0.0002182829999810565 s。
Find the treasure!
在有Cache的情況下,運(yùn)行花費(fèi)了0.00011638000000857573 s。
有Cache比沒Cache快0.00010190299997248076 s。
注記:運(yùn)行這個(gè)示例時(shí)我的電腦配置如下
CPU:AMD Ryzen 5 2600 RAM:Kingston HyperX 8Gigabytes 2666
約使用7個(gè)月。
這個(gè)裝飾器可以在函數(shù)運(yùn)行時(shí)記錄它的輸入值與運(yùn)行結(jié)果。當(dāng)元組('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth')出現(xiàn)第二次時(shí),加了這個(gè)裝飾器的函數(shù)find_the_treasure_quickly
不會(huì)再次在遞歸時(shí)對(duì)這個(gè)元組進(jìn)行查找,而是直接在“備忘錄”中找到運(yùn)行結(jié)果并返回!
到此,關(guān)于“Python裝飾器功能介紹”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!