Python3 装饰器笔记

装饰器(decorator):

  1>定义: 本质是函数,功能是用来装饰其他函数,为其他函数添加附加功能
  2>原则:(1)不能修改被装饰函数的源代码;(2);不能修改呗装饰的函数的调用方式

  实现装饰器知识储备:(1)函数即变量(2)高阶函数(满足其一就是:一个函数作为另一个函数的入参;返回值包含函数名(3)嵌套函数
  高阶函数 + 嵌套函数 = 修饰器

1.简单的装饰器,统计接口运行时间

输出结果:

2.模拟某些函数需要登陆验证,验证方式分为本地和ldap验证(完整版)

 

不足之处,请各位大佬指正!

userName,passWord ="Bert","abc123" #假设是数据库用户名密码
def auth(auth_type):
def outer_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type == 'local':
user_name =input('Username:').strip()
pass_word =input('Password:').strip()
if user_name == userName and pass_word == passWord:
print("用户名密码验证成功!")
return func(*args,**kwargs)
else:
print("用户名密码验证失败!")
elif auth_type == 'ldap':
print('ldap方式验证登录。。。')
return func(*args,**kwargs)
return wrapper
return outer_wrapper

def index():
print('in the index')
return 'index'
@auth(auth_type="local") #auth_type装饰器最外层函数的入参
def home():
print('in the home')
return 'home'

@auth(auth_type="ldap")
def bbs():
print('in the bbs')
return 'bbs'

index()
home()
bbs()

猜你喜欢

转载自www.cnblogs.com/bert227/p/9299637.html
今日推荐