# 要求二:定义用户类,定义属性db,执行obj.db可以拿到用户数据结构 class User: dbfile = 'user.db' def __init__(self,username): self.username = username @property #定义一个操作数据的属性 def db(self): with open (self.dbfile,encoding= 'utf-8') as f_read: for data_line in f_read: data_line = eval(data_line) #将拿到的数据结果从str 转化成 dict return data_line #返回一个转化成功的dict user1 = User('egon') print (user1.db[user1.username]) print (user1.db[user1.username]["password"]) #通过用户名获取相应的密码
用户类:(操作对象)
import time
class User:
db_path='user.db'
def __init__(self,name):
self.name=name
@property
def db(self): #设置db属性
with open(self.db_path,'r') as read_file:
info=read_file.read()
return eval(info) #调用db属性返回所有数据行
@db.setter #为属性db添加可修改功能
def db(self,value):
with open(self.db_path,'w') as write_file:
write_file.write(str(value))
write_file.flush()
@property
def locktime(self):
result = self.db[self.name]['timeout'] - time.time()
return result #获取锁定时间
@locktime.setter
def locktime(self,value):
pass
def login(self):
self.starttime = time.localtime(time.time()).tm_sec
data=self.db
t = time.localtime(time.time() - self.starttime) #登录最后时间 - 一开始登录的时间= 用户在线时长
if data[self.name]['status']:
print('%s已经登录 在线时长是%02d:%02d:%02d'%(self.name,t.tm_hour,t.tm_min,t.tm_sec))
return True
if data[self.name]['timeout'] < time.time():
count=0
self.locktime = 100
while count < 3: #三次锁定
passwd=input('password>>: ')
if not passwd:continue
if passwd == data[self.name]['password']:
data[self.name]['status']=True #如果登录成功把相应状态值 修改成True
data[self.name]['timeout']=0 #登录成功,相应用户的timeout设置为0
self.db=data #调用db.setter g更新数据
print("欢迎 %s 登录系统"%self.name)
break
count+=1 #密码录入错,累计加-
else:
# data[self.name]['timeout']=time.time()+100
data[self.name]['timeout'] =100 + time.time() #100秒就退出自动锁定
self.db=data
self.starttime = time.localtime(time.time()-self.starttime) #登录最后时间
else:
print('账号已经锁定%.2f秒'%self.locktime) #调用 locktime 属性
def logout(self):
data = self.db
flag = True
if data[self.name]['status']:
while flag:
# if time.time() - self.starttime > 30:
anser = input("%s 是否要退出?"%self.name)
if anser.lower() == "y":
data[self.name]['status'] = False
print("%s 已经成功退出"% self.name)
# data[self.name]['timeout'] = 0
self.db = data
flag = False
else:
break
else:
return False
u1=User('egon')
u1.login()
u2=User('alex')
u2.login()
u1.logout()
u2.logout()