详解Python装饰器
2019/7/14 23:25:00
本文主要是介绍详解Python装饰器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1. 定义
本质是函数,用来装饰其他函数,为其他函数添加附加功能
2. 原则
a. 不能修改被装饰函数的源代码
b. 不能修改被装饰的函数的调用方式
3. 实现装饰器知识储备
a. 函数就是变量
b. 高阶函数
i. 把一个函数当作实参传给另外一个函数,在不修改被装饰函数源代码情况下为其添加功能
ii. 返回值中包含函数名, 不修改函数的调用方式
c. 嵌套函数
高阶函数+嵌套函数==》装饰器
# 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装饰器详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!
这篇关于详解Python装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战