首页 > 代码库 > python 作业一4-10

python 作业一4-10

作业一:为程序加上测量运行时间的装饰器

 1 import time
 2 def timer(next):
 3     def wrapper(*args,**kwargs):
 4         start_time = time.time()
 5         next(*args,**kwargs)
 6         stop_time = time.time()
 7         print("run time in %s "%(stop_time - start_time))
 8 
 9     return wrapper
10 @timer
11 def index():
12     time.sleep(1)
13     print("welcome ")
14 
15 index()

作业二:利用装饰器和读写文件的方式控制用户登录

 1 def auth_type(auth_type):
 2     def auth(next):
 3         def wrapper(*args,**kwargs):
 4             if auth_type == file:
 5                 lock = {}
 6                 flag =True
 7                 with open("username.txt") as f_user, open("locked.txt", "a+") as f_lock, open("f_logged", "a+") as f_logged:
 8                     while flag:
 9                         lock_count = 0
10                         f_lock.seek(0)
11                         f_user.seek(0)
12                         f_logged.seek(0)
13                         user_name = input("请输入你的帐号:")
14                         for logged_in in f_logged:
15                             if  user_name ==logged_in.strip():
16                                 print("登陆成功!")
17                                 return  next(*args,**kwargs)
18                         passwd = input("请输入你的密码:")
19                         for user_lock in f_lock:
20                             if user_lock.strip() == user_name:
21                                 print("此帐号已被锁定!")
22                                 lock_count = 1
23                                 break
24                         for user in f_user:
25                             user_f, passwd_f = user.strip().split("----")
26                             if user_f == user_name and lock_count == 0:
27                                 if passwd_f == passwd:
28                                     print("登陆成功!")
29                                     f_logged.write(user_name+\n)
30                                     return  next(*args,**kwargs)
31                                 else:
32                                     if user_name in lock:
33                                         lock[user_name] += 1
34                                     else:
35                                         lock[user_name] = 1
36                                         break
37                                     print("登录失败!")
38                             if user_name in lock and lock[user_name] >= 3:
39                                 print("错误次数过多,帐号锁定!")
40                                 f_lock.write(user_name + \n)
41                                 lock.pop(user_name)
42                         print("登录失败! ")
43             elif auth_type == "sql":     print("峰哥还没教")
44         return wrapper
45     return auth
46 @auth_type(auth_type="file")
47 def index():
48     print("欢迎")
49 
50 index()

 

python 作业一4-10