python_选课系统

import sys
import pickle
import os

USERINFO = r'C:Users12078PycharmProjectsOldBoy选课系统userinfo'
STUINFO = r'C:Users12078PycharmProjectsOldBoy选课系统stuinfo'
COURSEINFO=r'C:Users12078PycharmProjectsOldBoy选课系统courinfo'
COURSE_LIST=r'C:Users12078PycharmProjectsOldBoy选课系统courinfo_list'
STU_COURSEINFO=r'C:Users12078PycharmProjectsOldBoy选课系统stu_courinfo'

class Course(object):

    def __init__(self,name,price,period):
        self.name = name
        self.price = price
        self.period = period

class Student(object):
    opt_lst = [('查看课程', 'show_courses'),('选择课程','choose_course'),
               ('查看已选课程', 'show_selected'), ('退出', 'exit')]
    def __init__(self,name):
        self.name = name
        self.courses = []

    def show_courses(self):
        with open(COURSE_LIST, mode='r', encoding='utf-8') as f:
            for line in f:
                print(line.strip())

    def choose_course(self):
        # pass  # 设计一个数据结构,将student和 course同时存进去
        courses=[]
        with open(COURSE_LIST, mode='r', encoding='utf-8') as f:
            for line in f:
                courses.append(line.strip())
        for index,c in enumerate(courses,1):
            print(index,c)
        num=int(input("请选择要选择的课程序号: "))
        dic={}
        flag=True
        if os.path.getsize(STU_COURSEINFO) > 0:
            with open(STU_COURSEINFO, mode='rb') as f:
                while True:
                    try:
                        dic = pickle.load(f)
                        if self.name in dic:
                            self.courses=dic[self.name]
                        else:
                            self.courses=[]
                        if courses[num - 1] in self.courses:
                            print("该课程已经选择过了,请选择其他课程!")
                            flag=False
                        else:
                            self.courses.append(courses[num - 1])
                            dic[self.name] = self.courses
                    except EOFError:
                        break
        else:
            print("here")
            self.courses=[]
            self.courses.append(courses[num - 1])
            dic[self.name] = self.courses
        if flag:
            with open(STU_COURSEINFO, mode='wb') as f:    # 覆盖
                pickle.dump(dic, f)  # 将实例化对象 pickle进文件
                print('%s课程创建成功' % courses[num-1])

    def show_selected(self):
        with open(STU_COURSEINFO, mode='rb') as f:
            while True:
                try:
                    dic = pickle.load(f)
                    if self.name in dic:
                        print(dic[self.name])
                        break
                except EOFError:
                    print("没有此学生的选课信息")
                    break

    def exit(self):
        sys.exit()

    @staticmethod
    def init(ret):
        with open(STUINFO,'rb') as f:
            while True:
                try:
                    obj = pickle.load(f)
                    if obj.name == ret[0]:
                        return obj
                except EOFError:print('没有这个学生,出现了不可思议的错误!')

class Manager(object):
    opt_lst = [('创建课程','create_course'),('创建学生','create_student'),
               ('查看课程','show_courses'),('查看学生','show_students'),
               ('查看学生和已选课程','show_stu_course'),('退出','exit')]
    def __init__(self,name):
        self.name = name

    # 创建的课程对象直接pickle进到文件里。
    def create_course(self):
        cname = input("请输入课程的名字: ")
        cprice = input("请输入课程的价格: ")
        cperiod = input("请输入课程的周期: ")
        course = Course(cname, cprice, cperiod)
        with open(COURSE_LIST, mode='a', encoding='utf-8') as f:
            f.write('%s
' % (cname))  # 给定默认密码和身份  身份要和类重名方便使用反射
        with open(COURSEINFO, mode='ab') as f:
            pickle.dump(course, f)  # 将实例化对象 pickle进文件
        print('%s课程创建成功' % course.name)

    # 创建的学生对象直接pickle进到文件里,将学生的username,password,ident存到单独的文件夹里方便后面遍历。
    def create_student(self):
        usr = input('username :')
        stu = Student(usr)
        with open(USERINFO,mode = 'a',encoding='utf-8') as f:
            f.write('%s|123456|Student
'%(usr))  # 给定默认密码和身份  身份要和类重名方便使用反射
        with open(STUINFO,mode = 'ab') as f:
            pickle.dump(stu,f)                    # 将实例化对象 pickle进文件
        print('%s学生创建成功'%stu.name)

    def show_courses(self):
        with open(COURSE_LIST, mode='r', encoding='utf-8') as f:
            for line in f:
                print(line.strip())

    def show_students(self):
        with open(USERINFO, mode='r', encoding='utf-8') as f:
            # for line in f:
            #     print(line.strip())
            # 或:
            while True:
                text_line = f.readline()
                if text_line:
                    print(text_line.strip())
                else:
                    break

    def show_stu_course(self):
        if os.path.getsize(STU_COURSEINFO) > 0:
            with open(STU_COURSEINFO, mode='rb') as f:
                while True:
                    try:
                        dic = pickle.load(f)
                        print(dic)
                        for k,v in dic.items():
                            c_list=";".join(v)
                            print('%s选择的课程是%s'%(k,c_list))
                    except EOFError:
                        break
        else:
            print("没有任何学生的选课信息。")

    def exit(self):
        sys.exit()

    @classmethod
    def init(cls,ret):
        obj = cls(ret[0])  # 实例化一个 Manager对象返回
        return obj

# 用户 输入用户名 密码 判断用户是否合法和身份是啥?
def login():
    '''

    :return: 登录成功:用户名,身份
              登录失败:False
    '''
    username = input('username :')
    password = input('password :')
    with open(USERINFO,encoding='utf-8') as f:
        for line in f:
            usr,pwd,ident = line.strip().split('|')
            if usr == username and password == pwd:
                return usr,ident  # 返回的是个元组  如: ('alex', 'Manager')
        else:
            return False

ret = login()
# print(ret)  # ('alex', 'Manager')
if ret:
    print('登录成功,%s,欢迎使用选课系统'%ret[0])
    if hasattr(sys.modules[__name__],ret[1]):
        cls = getattr(sys.modules[__name__],ret[1])   # 第一次使用反射,获取身份

    obj = cls.init(ret)  # 返回一个 Manager或 Student对象
    while True:
        for index,opt in enumerate(cls.opt_lst,1):
            print(index,opt[0])
        num = int(input('您要选择的操作 :').strip())
        if hasattr(obj,cls.opt_lst[num-1][1]):
            getattr(obj,cls.opt_lst[num-1][1])()     # 第二次使用反射,调用各自方法列表里的方法  Manager和Student里都有一个 opt_lst
else:
    print('登录失败')



原文地址:https://www.cnblogs.com/Collin-pxy/p/13034152.html