• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解Python装饰器

python 搞代码 4年前 (2022-01-07) 20次浏览 已收录 0个评论

这篇文章主要介绍了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<mark style="color:transparent">来源gaodaimacom搞#代%码网</mark>() Decorator

以上所述是小编给大家介绍的Python装饰器详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对gaodaima搞代码网网站的支持!

以上就是详解Python装饰器的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解Python装饰器

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址