詳解Python裝飾器
1. 定義
本質(zhì)是函數(shù),用來裝飾其他函數(shù),為其他函數(shù)添加附加功能
2. 原則
a. 不能修改被裝飾函數(shù)的源代碼
b. 不能修改被裝飾的函數(shù)的調(diào)用方式
3. 實現(xiàn)裝飾器知識儲備
a. 函數(shù)就是變量
b. 高階函數(shù)
i. 把一個函數(shù)當作實參傳給另外一個函數(shù),在不修改被裝飾函數(shù)源代碼情況下為其添加功能
ii. 返回值中包含函數(shù)名, 不修改函數(shù)的調(diào)用方式
c. 嵌套函數(shù)
高階函數(shù)+嵌套函數(shù)==》裝飾器
# Author: Lockegogo
user, passwd = 'LK', '130914'
def auth(auth_type):
print('auth func:', auth_type)
def outher_wrapper(func):
def wrapper(*args, **kwargs):
print('wrapper func:', *args, **kwargs)
if auth_type == 'local':
username = input('username:').strip()
password = input('password:').strip()
if user == username and password == passwd:
print('\033[32;1mUser has passed authentication\033[0m')
res = func(*args, **kwargs)
return res
else:
exit('\033[32;1mInvalid Username or password\033[0m')
elif auth_type == 'ldap':
print('ldap,不會')
return wrapper
return outher_wrapper
def index():
print('welcome to index page')
@auth(auth_type='local') # home = outher_wrapper(home)
def home():
print('welcome to home page')
return 'from home'
@auth(auth_type='ldap')
def bbs():
print('welcome to bbs page')
index()
print(home())
bbs()
Decorator
以上所述是小編給大家介紹的Python裝飾器詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
python多線程多并發(fā)啟動appium服務(wù)的實現(xiàn)
使用Dos命令或者bat批處理來手動啟動appium服務(wù),啟動效率低下,本文主要介紹了python多線程多并發(fā)啟動appium服務(wù)的實現(xiàn),具有一定的 參考價值,感興趣的可以了解一下2024-02-02
使用sklearn之LabelEncoder將Label標準化的方法
今天小編就為大家分享一篇使用sklearn之LabelEncoder將Label標準化的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
python字典中g(shù)et()函數(shù)的基本用法實例
在字典內(nèi)置的方法中,想說的方法為get,這個方法是通過鍵來獲取相應(yīng)的值,但是如果相應(yīng)的鍵不存在則返回None,這篇文章主要給大家介紹了關(guān)于python字典中g(shù)et()函數(shù)的基本用法,需要的朋友可以參考下2022-03-03
python用match()函數(shù)爬數(shù)據(jù)方法詳解
在本篇文章里小編給大家整理了關(guān)于python用match()函數(shù)爬數(shù)據(jù)方法以及相關(guān)知識點,需要的朋友們學習下。2019-07-07
Pytorch GPU顯存充足卻顯示out of memory的解決方式
今天小編就為大家分享一篇Pytorch GPU顯存充足卻顯示out of memory的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python利用卡方Chi特征檢驗實現(xiàn)提取關(guān)鍵文本特征
卡方檢驗最基本的思想就是通過觀察實際值與理論值的偏差來確定理論的正確與否。本文將利用卡方Chi特征檢驗實現(xiàn)提取關(guān)鍵文本特征功能,感興趣的可以了解一下2022-12-12

