脱产班第四次大作业-学生选课系统

https://www.cnblogs.com/Eva-J/articles/9235899.html

Low Ver.

#!/usr/bin/env python
# encoding: utf-8
# Author: MeiMeiLong <[email protected]>
# Create Date: 2019-03-29 15:47:08
# Last Modified: 2019-03-31 11:41:25
# Description:
import os
import json
import pickle
import hashlib

class Account(object):

    def __init__(self,username,password,userfile = 'userinfo.json',courcefile = 'courceinfo.pickle'):
        self.username = username
        self.__password = password
        self.userfile = userfile
        self.courcefile = courcefile

    def __GetJson(self):
        with open(self.userfile,mode='r',encoding='utf-8') as jsonfile:
            return json.load(jsonfile)

    def __PutJson(self,user_dic):
        with open(self.userfile,mode='w',encoding='utf-8') as jsonfile:
            json.dump(user_dic,jsonfile,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
            return True

    def __md5encry(self,passwd):
        md5 = hashlib.md5()
        md5.update(passwd.encode('utf-8'))
        return  md5.hexdigest()

    def __CheckAccount(self):
        if os.path.exists(self.userfile):
            if self.__GetJson() == '':
                self.__PutJson({'Student':dict(),'Administrator':dict()})
                return '账户初始化完成'
        else:
                self.__PutJson({'Student':dict(),'Administrator':dict()})
                return '账户初始化完成'

    def login(self):
        self.__CheckAccount()
        UserInfo = self.__GetJson()
        for character in UserInfo:
            if UserInfo[character].get(self.username):
                if UserInfo[character][self.username] == self.__md5encry(self.__password):
                    return character
                else:
                    print('用户名或密码错误')
                    return False,False
        else:
            print(f'用户:{self.username}不存在')
            return False

    def register(self,character='Student'):
        self.__CheckAccount()
        UserInfo = self.__GetJson()
        if UserInfo[character].get(self.username):
            print(f'用户:{self.username}已存在')
            return False
        else:
            UserInfo[character][self.username] = self.__md5encry(self.__password)
            if self.__PutJson(UserInfo):
                return character

class Cources(object):
    """
    课程并没有什么动作,所以我们只设计属性不设计方法。
    """
    def __init__(self,name,price,cycle,teacher):
        self.name = name
        self.price = price
        self.cycle = cycle
        self.teacher = teacher

#Student
#{{{
class Student(Account,Cources):
    """
    方法:查看可选课程、选择课程、查看所选课程、退出程序 
    """
    def __init__(self,username,password,userfile = 'userinfo.json',courcefile = 'courceinfo.pickle',cources=None):
        super().__init__(username,password,userfile = 'userinfo.json',courcefile = 'courceinfo.pickle')
        self.cources = cources

    def __GetCource(self,f=None):
        if f is None:
            try:
                with open(self.courcefile,mode='rb') as pickfile:
                    return pickle.load(pickfile)
            except EOFError:
                return []
        else:
            try:
                with open(self.courcefile,mode='rb') as pickfile:
                    return pickle.load(pickfile)
            except EOFError:
                return []


    def __PutCource(self,cource_lst,f=None):
        if f is None:
            with open(self.courcefile,mode='wb') as pickfile:
                pickle.dump(cource_lst,pickfile)
                return True
        else:
            with open(f,mode='wb') as pickfile:
                pickle.dump(cource_lst,pickfile)
                return True

    def ViewCources(self,cources_lst=list()):
        #return self.__GetCource(__userfile)
        for cource in self.__GetCource():
            dic = dict()
            dic['name'] = cource.name
            dic['price'] = cource.price
            dic['cycle'] = cource.cycle
            dic['teacher'] = cource.teacher
            cources_lst.append(dic)
        return cources_lst

    def ChoiceCource(self,choice_lst=list()):
        for dic in self.__GetCource():
            print(f"名称:{dic.name},价格:{dic.price},周期:{dic.cycle},老师:{dic.teacher}")
            select = input('是否选择此科目(Y/N):').strip()
            if select.upper() == 'Y':
                choice_lst.append(dic)
        else:
            self.cources = choice_lst
            cachefile = self.username.username + '.pickle'
            self.__PutCource(self.cources,cachefile)
            return self.cources

    def SelectedCourse(self):
        cachefile = self.username.username + '.pickle'
        cource_lst = self.__GetCource(cachefile)
        for lesson in cource_lst:
            print(f'选择了{lesson.name}科目')
#}}}
#Administrator
###{{{
class Administrator(Account,Cources):
    """
    方法:创建课程、创建学生学生账号、查看所有课程、查看所有学生、查看所有学生的选课情况、退出程序
    """
    def __init__(self,username,password,userfile = 'userinfo.json',courcefile = 'courceinfo.pickle'):
        super().__init__(username,password,userfile = 'userinfo.json',courcefile = 'courceinfo.pickle')

    def __GetCource(self,f=None):
        if f is None:
            try:
                with open(self.courcefile,mode='rb') as pickfile:
                    return pickle.load(pickfile)
            except EOFError:
                return []
        else:
            try:
                with open(self.courcefile,mode='rb') as pickfile:
                    return pickle.load(pickfile)
            except EOFError:
                return []

    def __PutCource(self,cource_lst):
        with open(self.courcefile,mode='wb') as pickfile:
            pickle.dump(cource_lst,pickfile)
            return True

    def CreateCource(self,cource_name_lst=list()):
        Cource_lst = self.__GetCource()
        name = input('课程名称:').strip()
        price = input('课程价格:').strip()
        cycle = input('课程周期:').strip()
        teacher = input('教课老师:').strip()
        name = Cources(name,price,cycle,teacher)
        for cource in Cource_lst:
            cource_name_lst.append(cource.name)
        if name.name not in cource_name_lst:
            Cource_lst.append(name)
        else:
            print('课程已存在')
            return False
        ret = self.__PutCource(Cource_lst)
        if ret:
            print('课程添加成功')
            return True

    def CreateAccount(self):
        return Register()

    def ViewCources(self,cources_lst=list()):
        #return self.__GetCource(__userfile)
        for cource in self.__GetCource():
            dic = dict()
            dic['name'] = cource.name
            dic['price'] = cource.price
            dic['cycle'] = cource.cycle
            dic['teacher'] = cource.teacher
            cources_lst.append(dic)
        return cources_lst

    def __GetJson(self):
        with open(self.userfile,mode='r',encoding='utf-8') as jsonfile:
            return json.load(jsonfile)

    def ViewStudents(self):
        return [ student for student in self.__GetJson()['Student'] ]

    def ViewStudent_Cources(self):
        Student = self.ViewStudents()
        for stu in Student:
            if os.path.exists(stu + '.pickle'):
                stu_cource = self.__GetCource(stu +'.pickle')
                lesson = [ i.name for i in stu_cource]
                print(f'学生{stu}选择了{",".join(lesson)}.')
            else:
                print(f'学生{stu}没有选择课程.')
#}}}
def Register():
    user = input('输入你的用户名:'.strip())
    passwd = input('输入你的密码:'.strip())
    character = input('输入用户的角色(Administrator/Student):'.strip())
    character = 'Student' if character is '' or character == 'Student' else 'Administrator'
    user = Account(user,passwd)
    chara = user.register(character)
    if chara:
        print(f'用户:{user.username}以{chara}身份注册成功')
        return chara,True

def Login():
    user = input('输入你的用户名:'.strip())
    passwd = input('输入你的密码:'.strip())
    user = Account(user,passwd)
    chara = user.login()
    if chara:
        print(f'用户:{user.username}以{chara}身份登陆成功')
        User = globals()[chara](user,passwd)
        return chara,User

def Logout():
    print('登出!')
    return False

def Menu(character='Nobody'):
    menu_title = {
            'Nobody': ['登陆','注册','退出'],
            'Student': ['查看所有课程','选择课程','查看所选课程','账号登出'],
            'Administrator': ['创建课程','创建学生账号','查看所有课程','查看所有学生','查看所有学生的选课情况','账号登出'],
            }
    menu_action = {
            'Nobody':{'1':Login,'2':Register,'3':Logout},
            'Student':{'1':'ViewCources','2':'ChoiceCource','3':'SelectedCourse','4':Logout},
            'Administrator':{'1':'CreateCource','2':'CreateAccount','3':'ViewCources','4':'ViewStudents','5':'ViewStudent_Cources','6':Logout},
            }

    print('学生选课系统'.center(40,'='))
    print(f'所属用户:{character}'.rjust(42,' '))
    for num,title in enumerate(menu_title[character]):
        print(f'\033[32;1m{str(num+1)}、{title}\033[0m')
    select = input('>>>').strip()
    if select.isdigit():
        if int(select) not in range(1,len(menu_action[character])+1):
            print('请输入正确的数字')
            return None
    else:
            print('请输入正确的数字')
            return None

    if callable(menu_action[character][select]):
        return menu_action[character][select]()
    else:
        return menu_action[character][select]

if __name__ == "__main__" :
    exit_flagI = True
    while exit_flagI:
        User = Menu()
        if User is False or User is None:
            exit_flagI = False
            continue
        elif User[1] == True:
            exit_flagI = False
            continue

        if User:
            exit_flagII = True
            while exit_flagII:
                character,class_user = User
                Act = Menu(character)
                if Act is False:
                    exit_flagII = False
                    continue
                elif Act is None:
                    continue

                if hasattr(class_user,Act):
                    if Act == 'ViewCources':
                        ret = getattr(class_user,Act)
                        print('所有课程'.center(40,'='))
                        for dic in ret():
                            print(f"名称:{dic['name']},价格:{dic['price']},周期:{dic['cycle']},老师:{dic['teacher']}")
                    elif Act == 'ViewStudents':
                        ret = getattr(class_user,Act)()
                        print('有学生:')
                        for student in ret:
                            print(f'{student}',end=' ')
                        else:
                            print('\n')
                    else:
                        ret = getattr(class_user,Act)()

猜你喜欢

转载自www.cnblogs.com/meilong/p/tuo-chan-ban-di-si-ci-da-zuo-yexue-sheng-xuan-ke-x.html
今日推荐