詳解Python裝飾器
1. 定義
本質是函數(shù),用來裝飾其他函數(shù),為其他函數(shù)添加附加功能
2. 原則
a. 不能修改被裝飾函數(shù)的源代碼
b. 不能修改被裝飾的函數(shù)的調用方式
3. 實現(xiàn)裝飾器知識儲備
a. 函數(shù)就是變量
b. 高階函數(shù)
i. 把一個函數(shù)當作實參傳給另外一個函數(shù),在不修改被裝飾函數(shù)源代碼情況下為其添加功能
ii. 返回值中包含函數(shù)名, 不修改函數(shù)的調用方式
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)站的支持!
相關文章
Python批量發(fā)送post請求的實現(xiàn)代碼
昨天學了一天的Python(我的生產(chǎn)語言是java,也可以寫一些shell腳本,算有一點點基礎),今天有一個應用場景,就正好練手了2018-05-05研究Python的ORM框架中的SQLAlchemy庫的映射關系
這篇文章主要介紹了研究Python的ORM框架中的SQLAlchemy庫的映射關系,SQLAlchemy庫是一個常見的Python中操作數(shù)據(jù)庫的工具,需要的朋友可以參考下2015-04-04淺談django2.0 ForeignKey參數(shù)的變化
今天小編就為大家分享一篇淺談django2.0 ForeignKey參數(shù)的變化,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08