利用面向对象写的登录与注册

登陆成功之后修改密码

import os


# 定义一个用户类,用户名和密码是这个类的属性,实例化两个用户,分别有不同的用户名和密码
# 登陆成功之后才创建用户对象
# 设计一个方法 修改密码
def login(user, passwd):
    user_pwd_dict = {}
    with open("ab.txt", encoding="utf-8") as f:
        for line in f:
            name, pwd = line.strip().split("|")
            user_pwd_dict[name] = pwd
    if user in user_pwd_dict and passwd == user_pwd_dict[user]:
        return True
    else:
        return False


class User(object):
    def __init__(self, usname, passwd):
        self.usname = usname
        self.passwd = passwd

    def change_pwd(self):
        oldpwd = input("请输入原密码")
        newpwd = input("请输入新密码")
        flag = False
        with open("ab.txt", encoding="utf-8") as f1, open("ac.txt", mode="w", encoding="utf-8") as f2:
            for line in f1:
                usname, pw = line.strip().split("|")
                if usname == self.usname and pw == oldpwd:
                    line = "%s|%s\n" % (usname, newpwd)
                f2.write(line)
        os.remove("ab.txt")
        os.rename("ac.txt", "ab.txt")
        return flag


username = input("请输入用户名")
password = input("请输入密码")
ret = login(username, password)
if ret:
    print("登录成功")
    obj = User(username, password)
    res = obj.change_pwd()
    if res:
        print('修改成功')
    else:
        print("修改失败")
else:
    print("登录失败")

2.登录与注册

class User:
def __init__(self, name, pwd):
self.name = name
self.pwd = pwd


class Account:
def __init__(self):
self.user_list = []

def login(self):
# 登录
username = input('用户名 :').strip()
password = input('密 码 :').strip()
with open("a.txt", mode="r", encoding="utf-8") as f:
for user in f:
user_line = user.strip().split("|")
if username == user_line[0] and password == user_line[1]:
print('登录成功')
break
else:
print('登录失败')

def register(self):
# 注册
username = input('请输入用户名 :').strip()
password = input('请输入密 码 :').strip()
password2 = input('密码确认 :').strip()
if password == password2:
with open("a.txt", mode="a", encoding="utf-8") as f:
f.write(username + "|" + password + "\n")
user = User(username, password)
self.user_list.append(user)
print('注册成功')
else:
print('注册失败,您两次输入的密码不一致')

def run(self):
opt_lst = ['登录', '注册']
while True:
for index, item in enumerate(opt_lst, 1):
print(index, item)
num = input('请输入您需要的操作序号 :').strip()
if num == '1':
self.login()
elif num == '2':
self.register()
elif num.upper() == 'Q':
break


if __name__ == '__main__':
obj = Account()
obj.run()
posted @ 2019-12-30 19:54  菜鸟学小白  阅读(592)  评论(0编辑  收藏  举报
ヾ(≧O≦)〃嗷~