join_mark

 

python_装饰器

一.装饰器
#装饰器:本质就是函数,功能是为其它函数添加附加功能
#原则:
#1.不修改被修饰函数的源代码
#2.不修改被修饰函数的调用方式
#装饰器=高级函数 + 函数嵌套 + 闭包


#高级函数
#高级函数的定义:1函数接收的参数是一个函数名 2.函数的返回值是一个函数名 3.满足其一,称为高级函数

#1函数接收的参数是一个函数名
# def foo():
# print("你好")
#
# def test1(func):
# print(func)
# func()
# test1(foo)

#2.函数的返回值是一个函数名

# def foo():
# print('from the foo')
# def test1(func):
# return func
# res=test1(foo)
# print(test1(foo))
# print(res)

#用高级函数来实现装饰器(发现多运行了一次,无法满足装饰器的要要求)
# import time
# def foo():
# time.sleep(1)
# print('from the foo')
# def timer(func):
# start_time=time.time()
# func()
# stop_time=time.time()
# print("函数运行时间:%s" %(stop_time-start_time))
# return func

# foo=timer(foo)
# foo()


#函数嵌套
# def father(auto_type):
# print('from father is %s' %auto_type)
# def son():
# name='milk'
# print('form son is %s'%auto_type)
# def grandson():
# print("from grandson is %s" %auto_type)
# grandson()
# son()
# print(locals()) #打印两个局部变量,一个是jack,一个是函数son(函数也是变量)
# father('jack')

#闭包就是作用域


二.装饰器架子
# import time
# def timer(func): #func=test内存地址
# def wrapper():
# start_time=time.time()
# func() #执行test()函数
# stop_time=time.time()
# print('运行时间是%s' %(stop_time-start_time))
# return wrapper
# @timer # @timer 就相当于test=timer(test)
# def test():
# time.sleep(2)
# print('test函数运行完毕')
#
# # test=timer(test) #返回wrapper的内存地址,此行与12行需要实现的效果是一样的
# test() #执行wrapper函数

三、装饰器实现多个验证方式

#多种验证方式
# user_list=[{'name':'jack','passwd':'abc'},
# {'name':'nice','passwd':'abc'},
# {'name':'milk','passwd':'abc'},
# ]
# current_dic={'username':None,'Login':False}
# def auth(auto_type='filedb'):
# def auto_fucn(func):
# def wrapper(*args,**kwargs):
# print('认证类型是:',auto_type)
# if auto_type =='filedb':
# if current_dic['username'] and current_dic['Login']:
# res=func(*args,**kwargs)
# return res
# username=input('用户名:').strip()
# passwd = input('密码:').strip()
# for user_dic in user_list:
# if username ==user_dic['name'] and passwd ==user_dic['passwd']:
# current_dic['username']=username
# current_dic['Login']=True
# res=func(*args,**kwargs)
# return res
# else:
# print('用户或密码不对!')
# elif auto_type == 'ldap':
# print('认证类型:ldap')
# res = func(*args, **kwargs)
# return res
# else:
# print('其它验证方式')
# res = func(*args, **kwargs)
# return res
# return wrapper
# return auto_fucn
#
# @auth(auto_type='filedb') #auto_fucn=auth(auto_type='filedb') -> auto_fucn 附加一个auth_type
# def index():
# print('欢迎来到首页')
# @auth(auto_type='ldap')
# def home(name):
# print('%s欢迎来go home'%name)
# @auth(auto_type='mik')
# def shopping_car(name):
# print('%s购物车里有【%s ,%s,%s】'%(name,'电脑','衣服','图书'))
#
# # print('before:',current_dic)
# index()
# # print('after:',current_dic)
# home('jack')
# shopping_car('jack')

posted on 2018-04-13 19:36  join_mark  阅读(100)  评论(0)    收藏  举报

导航