欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

详解Python装饰器

时间:2021-04-30 10:11:05|栏目: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代码

下一篇:Python使用shelve模块实现简单数据存储的方法

本文标题:详解Python装饰器

本文地址:http://www.codeinn.net/misctech/111635.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有