Python裝飾器的兩種使用心得
裝飾器的基礎使用(裝飾帶參函數(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ù)的時候由于返回的是inner的函數(shù)地址,所以函數(shù)的名稱也會改變 show_info.__name__會變成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')
這樣寫就不會改變被裝飾函數(shù)的名稱
裝飾器動態(tài)注冊函數(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()
個人心得
在閱讀裝飾器代碼時可以使用加(func_name)的方式
以為例
@commands.regist_cmd('s2')
def show_e():
print('show_e')
即 show_e = commands.regist_cmd('s2')(show_e)
到此這篇關于Python裝飾器的兩種使用的文章就介紹到這了,更多相關Python裝飾器使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python實現(xiàn)將文件夾下面的不是以py文件結尾的文件都過濾掉的方法
今天小編就為大家分享一篇python實現(xiàn)將文件夾下面的不是以py文件結尾的文件都過濾掉的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
python scipy.spatial.distance 距離計算函數(shù) ?
本文主要介紹了python scipy.spatial.distance 距離計算函數(shù),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
Python3實現(xiàn)帶附件的定時發(fā)送郵件功能
這篇文章主要為大家詳細介紹了Python3實現(xiàn)帶附件的定時發(fā)送郵件功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02

