Python裝飾器的兩種使用心得
裝飾器的基礎(chǔ)使用(裝飾帶參函數(shù))
def decorator(func): def inner(info): print('inner') func(info) return inner @decorator def show_info(info): print(info) show_info('hello')
防止裝飾器改變裝飾函數(shù)名稱(chēng)
裝飾器在裝飾函數(shù)的時(shí)候由于返回的是inner的函數(shù)地址,所以函數(shù)的名稱(chēng)也會(huì)改變 show_info.__name__會(huì)變成inner,防止這種現(xiàn)象可以使用functools
import functools def decorator(func): @functools.wraps(func) def inner(info): print('inner') func(info) return inner @decorator def show_info(info): print(info) show_info('hello')
這樣寫(xiě)就不會(huì)改變被裝飾函數(shù)的名稱(chēng)
裝飾器動(dòng)態(tài)注冊(cè)函數(shù)
此方法在Flask框架的app.Route()的源碼中體現(xiàn)
class Commands(object): def __init__(self): self.cmd = {} def regist_cmd(self, name: str) -> None: def decorator(func): self.cmd[name] = func print('func:',func) return func return decorator commands = Commands() # 使得s1的值指向show_h的函數(shù)地址 @commands.regist_cmd('s1') def show_h(): print('show_h') # 使得s2的值指向show_e的函數(shù)地址 @commands.regist_cmd('s2') def show_e(): print('show_e') func = commands.cmd['s1'] func()
個(gè)人心得
在閱讀裝飾器代碼時(shí)可以使用加(func_name)的方式
以為例
@commands.regist_cmd('s2') def show_e(): print('show_e')
即 show_e = commands.regist_cmd('s2')(show_e)
到此這篇關(guān)于Python裝飾器的兩種使用的文章就介紹到這了,更多相關(guān)Python裝飾器使用內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。