类来实现选课系统

选课系统:

功能介绍

  • 管理员:

    • 创建课程

    • 创建学生

    • 查看课程

    • 查看学生

    • 查看学生选课

    • 退出程序

  • 学生:

    • 查看可选课程

    • 查看已选课程

    • 进行选课

    • 修改密码

    • 退出程序

细节问题

1、登录时,直接输入用户名和密码,要能根据不同角色(学生、管理员)进入不同功能选项。

2、要创建三个文件

  • course_file: 保存课程类的对象,用pickle格式保存。

  • login_file: 保存格式,用户名|密码|(学生类名/管理员类名)

  • student_file:保存学生类的对象,用pickle格式保存

3、创建学生时,要同时对login_file和student_file两个文件实现更新

代码:

import pickle
import sys
COURSE_PATH = 'course_file' #课程对象的文件路径
STUDENT_PATH = 'student_file'#学生对象的文件路径
LOGIN_PATH = 'login_file'#登录用户名密码,角色的文件路径
#读取course_file中的课程对象,读取student_file中的学生对象,list
def read_student_course(path):
   lis = []
   with open(path,'rb') as fp:
       while 1:
           try :
               obj = pickle.load(fp)
               lis.append(obj)
           except EOFError:
               break
   return lis
#将更新的课程对象列表,重新写入到course_file
# 将更新后的学生对象列表,重新写到文件中student_file中 list
def write_student_course(lis,path):
   with open(path,'wb')as fp:
       for obj in lis:
           pickle.dump(obj,fp)
   return True
#读取Login_file文件,dic={'lhz':['lhz','123','student'],}
def read_login_file():
   dic={}
   with open(LOGIN_PATH,'r',encoding='utf-8')as fp:
       for line in fp:
           lis = line.strip().split('|')
           dic[lis[0]]=lis
   return dic
#将更新的用户密码字典写回,login_file文件
def write_login_file(dic):
   with open(LOGIN_PATH,'w',encoding='utf-8') as fp:
       for key in dic:
           msg = '|'.join(dic[key]) +'\n'
           fp.write(msg)
   return True
#查看课表
def show_course():
   lis = read_student_course(COURSE_PATH)
   co =1
   for obj in lis:
       print(f"{co}、{obj}")#在Course类中写了 __str__
       co+=1
class Course(object):
   def __init__(self,name,permi,price,teacher):
       self.name = name
       self.permi = permi
       self.price = price
       self.teacher = teacher
   def __str__(self):
       msg = self.name+':'+str(self.permi)+','+str(self.price)+','+self.teacher
       # msg = '123'
       return msg
class Student(object):
   opt_list = [
      ('查看课程','show_course'),('进行选课','select_course'),
      ('查看我的选课','show_self_cour'),('修改密码','chang_pwd'),('退出程序','exit'),
  ]
   def __init__(self,name):
       self.name = name
       self.select=[]
   def show_course(self):
       print(f'{"*-" * 3}>所有课程:')
       show_course()
       print(f'<{"-" * 10}')
   def select_course(self):
       while 1:
           print(f'{"*-" * 3}>所有课程:')
           show_course()
           print(f'<{"-" * 10}')
           num = input('输入你的选择(x/X退出):').strip()
           lis = read_student_course(COURSE_PATH)
           stu_lis = read_student_course(STUDENT_PATH)
           # for ou in stu_lis:
           #     print(ou.name)
           if num.isdecimal():
               num= int(num)
               if num>0 and num<=len(lis):
                   # print(f'选择课程{num}成功。')
                   # print('88行')
                   for obj in stu_lis:
                       if self.name == obj.name:  # 找到该学生对象
                           # print('91行')
                           for cou in obj.select:
                               if lis[num - 1].name == cou.name and lis[num - 1].teacher == cou.teacher:
                                   print('你已经选过该课程了。')
                                   break
                           else:
                               # print('97行')
                               obj.select.append(lis[num - 1])
                               print(f'恭喜选择课程{num}成功。')
                               write_student_course(stu_lis, STUDENT_PATH)
               else:
                   print('无此选择。')
           else:
               if num.upper()=='X':
                   print('退出选课界面')
                   break
               print('输入有误。')
   def show_self_cour(self):
       lis = read_student_course(STUDENT_PATH)
       for obj in lis:
           if self.name==obj.name:
               if obj.select:
                   co=1
                   print(f'--->{obj.name},选课记录')
                   for cou in obj.select:
                       print(f"{co},{cou}")
                       co+=1
                   print()
               else:
                   print(f'--->{obj.name},选课记录')
                   print('无选课记录。')
                   print()

               # for i,cou in enumerate(obj.select,1):
               #     print(f'{i},{cou}')
   def chang_pwd(self):
       dic = read_login_file()
       while 1:
           old = input('输入密码:').strip()
           if dic[self.name][1]==old:
               new = input('输入新密码:').strip()
               agan = input('确认密码:').strip()
               if new==agan:
                   print('修改密码成功。请重新登录。')
                   dic[self.name][1]=new
                   write_login_file(dic)
                   return 'LOGIN'
               else:
                   print('两次密码不一致!')
           else:
               print('密码错误。')
   def exit(self):
       return False
   @classmethod
   def init(cls, name):
       obj = Student(name)
       return obj
class Admin(object):
   opt_list=[
      ('创建课程','creat_course'),('创建学生','creat_stu'),
      ('查看课程','show_course'),('查看学生','show_student'),
      ('查看学生选课','show_stu_select'),('退出程序','exit'),
            ]
   def __init__(self,name):
       self.name=name
   def creat_course(self):
       while 1:
           name = input('输入课程名(X/x退出):').strip()
           if name.upper()=='X':
               break
           permi = input('输入课程周期:').strip()
           price = input('输入课程价格:').strip()
           teacher = input('输入授课老师:').strip()
           lis =read_student_course(COURSE_PATH)
           for obj in lis:
               if obj.name ==name and obj.teacher==teacher:
                   print('该课程已经存在了。')
                   break
           else:
               cou = Course(name,permi,price,teacher)
               lis.append(cou)
               ret = write_student_course(lis,COURSE_PATH)
               if ret:
                   print('创建课程成功。')
   def creat_stu(self):
       while 1:
           name = input('输入学生姓名(x/X退出):').strip()
           if name.upper()=='X':
               break
           dic = read_login_file()
           if name not in dic:
               dic = read_login_file()
               dic[name]=[name,'123','Student']
               write_login_file(dic)
               stu = Student(name)
               lis = read_student_course(STUDENT_PATH)
               lis.append(stu)
               ret=write_student_course(lis,STUDENT_PATH)
               if ret:
                   print('创建学生成功。')
           else:
               print('该学生已经存在了。')
   def show_course(self):
       print(f'{"*-"*3}>所有课程:')
       show_course()
       print(f'<{"-"*10}')
   def show_student(self):
       dic = read_login_file()
       print(f'{"*-"*3}>学生:')
       co=1
       for name in dic:
           if dic[name][-1]=='Student':
               print(F'{co}、{name}')
               co+=1
       print(f'<{"-"*10}')
   def show_stu_select(self):
       lis = read_student_course(STUDENT_PATH)
       for obj in lis :
           if obj.select:
               co = 1
               print(f'--->{obj.name},选课记录')
               for cou in obj.select:
                   print(f"{co},{cou}")
                   co += 1
               print()
           else:
               print(f'--->{obj.name},选课记录')
               print('无选课记录。')
               print()
   def exit(self):
       return False
   @classmethod
   def init(cls,name):
       obj = Admin(name)
       return obj
def run():
   while 1:
       name = input('输入用户名:').strip()
       pwd = input('输入密码:').strip()
       dic = read_login_file()
       flag=0
       tem=0
       for key in dic:
           if name ==key and pwd==dic[key][1]:
               flag=1
               print(f'登录成功。')
               if hasattr(sys.modules[__name__],dic[key][-1]):
                   cls = getattr(sys.modules[__name__],dic[key][-1])
                   #反射出类名来:Admin,Student
                   # obj=cls.init(name)#通过类名调用init方法,该方法是直接创建一个类对象。
                   obj = cls(name)
                   while 1:
                       print(f'{"-*"*5}{"功能"}{"-*"*5}')
                       for i ,tup in enumerate(cls.opt_list,1):
                           print(f'{i},{tup[0]}')
                       num = input('输入选择的功能:').strip()
                       if num.isdecimal():
                           num = int(num)
                           if num>0 and num<=len(cls.opt_list) and hasattr(obj,cls.opt_list[int(num)-1][-1]):
                               fun = getattr(obj,cls.opt_list[int(num)-1][-1])
                               if callable(fun):
                                   ret = fun()
                                   if ret==False:
                                       tem=1
                                       break
                                   elif ret =='LOGIN':
                                       break
                           else:print('无此选择')
                       else:
                           print('输入有误。')
       if flag==0:
           print('用户或密码错误。')
       if tem==1:
           print('退出系统。')
           break
run()



posted @ 2021-08-17 14:49  提笔按住它  阅读(55)  评论(0)    收藏  举报