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ù)名稱
裝飾器在裝飾函數(shù)的時(shí)候由于返回的是inner的函數(shù)地址,所以函數(shù)的名稱也會(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')
這樣寫就不會(huì)改變被裝飾函數(shù)的名稱
裝飾器動(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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中map和列表推導(dǎo)效率比較實(shí)例分析
這篇文章主要介紹了Python中map和列表推導(dǎo)效率比較,實(shí)例分析了Python中的map與列表的推導(dǎo)效率,需要的朋友可以參考下2015-06-06
python實(shí)現(xiàn)將文件夾下面的不是以py文件結(jié)尾的文件都過濾掉的方法
今天小編就為大家分享一篇python實(shí)現(xiàn)將文件夾下面的不是以py文件結(jié)尾的文件都過濾掉的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10
python scipy.spatial.distance 距離計(jì)算函數(shù) ?
本文主要介紹了python scipy.spatial.distance 距離計(jì)算函數(shù),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Python3實(shí)現(xiàn)帶附件的定時(shí)發(fā)送郵件功能
這篇文章主要為大家詳細(xì)介紹了Python3實(shí)現(xiàn)帶附件的定時(shí)發(fā)送郵件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
python 實(shí)現(xiàn)提取PPT中所有的文字
這篇文章主要介紹了python 實(shí)現(xiàn)提取PPT中所有的文字,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python實(shí)現(xiàn)發(fā)送郵件到自己郵箱
在日常開發(fā)中,我們經(jīng)常需要監(jiān)控應(yīng)用程序的狀態(tài),及時(shí)發(fā)現(xiàn)問題并采取措施解決。而通過郵件發(fā)送報(bào)警信息則是一種常見的實(shí)現(xiàn)方式。本文就來介紹一下Python實(shí)現(xiàn)發(fā)送郵件到自己郵箱的方法2023-04-04

