函数装饰器
#-----函数装饰器-----
1、作用域:L _E_G_B
2、高阶函数 a、函数名可以作为参数输入 b、函数名可以作为返回值
3、闭包
1 def outer(): 2 x = 10 3 def inner(): #inner是内部函数 4 print(x) #外部环境的一个变量 5 return inner #内部函数inner就是一个闭包 6 outer()() 7 8 #inner() #1、局部变量,全局变量无法调用
#-----关于闭包-----
闭包 = 函数 + 定义函数时的环境
#代码原则:开放封闭原则 代码书写原则(对修改封闭,对扩展开放)
#-----装饰器函数
1 import time 2 3 def show_time(f): #装饰器函数 4 def inner(): 5 start = time.time() 6 f() 7 time.sleep(1) 8 end = time.time() 9 print("spend %s"% (end-start)) 10 return inner 11 12 @show_time 13 def foo(): 14 print('test') 15 #foo=show_time(foo) 16 foo() 17 18 @show_time 19 def bar(): 20 print('bar') 21 # bar = show_time(bar) 22 bar() 23 24 def show_time(f): 25 def inner(x,y): 26 start = time.time() 27 f(x,y) 28 time.sleep(1) 29 end = time.time() 30 print(end-start) 31 return inner 32 33 @show_time 34 def add1(a,b): 35 print(a+b) 36 add1(1,2)
#-----装饰器加参数
1 def logger(flag='False'): 2 def show_time(f): 3 def inner(*args): 4 start_time = time.time() 5 f(*args) 6 time.sleep(1) 7 end_time = time.time() 8 print(end_time-start_time) 9 if flag == "True": 10 print('log!') 11 return inner 12 return show_time 13 14 @logger('True') 15 def add(*args): 16 sum1 = 0 17 for i in args: 18 sum1 += i 19 print(sum1) 20 21 add(1,2,4)
#-----用户信息登录验证小程序-----
#-----创建用名密码
1 import json 2 3 def create_user(a,b,c,d): 4 d = { 5 "name":a, 6 "passwd":b 7 } 8 with open(c,"w") as f: 9 json.dump(d,f) 10 create_user("dream","abc123","jd.json","jd_list") 11 create_user("rise","rise123","qq.json","qq_list") 12 create_user("wx","wx123","wx.json","wx_list")
#-----用户信息验证
1 import json 2 3 login_status = "False" 4 def login(auth_type): 5 def verify(func): 6 def inner(): 7 global login_status 8 flag = True 9 while flag: 10 c_list = ['jd','qq','wx'] 11 for i in c_list: 12 if auth_type == i.strip(): 13 files = auth_type 14 u_name = input("please input %s name:" % files).strip() 15 u_passwd = input("please input %s passwd:" % files).strip() 16 with open(("%s.json") % files, "r") as f: 17 data = dict(json.load(f)) 18 name = data["name"] 19 passwd = data["passwd"] 20 if u_name == name and u_passwd == passwd: 21 login_status = "True" 22 func() 23 flag = False 24 else: 25 func() 26 return inner 27 return verify 28 29 @login("jd") 30 def home(): 31 print("welcome to home page") 32 home() 33 34 @login("qq") 35 def finance(): 36 print("welcome to finance page") 37 finance() 38 39 @login("wx") 40 def book(): 41 print("welcome to book page") 42 book()