python day 12: 选课系统

python day 12

2019/10/18

学习资料来自老男孩教育

1. 通过类来创建选课系统

看完视频之后,自己折腾了一天才重新写出来,算是理解了。
程序结构

1.1 类库models.py

import os, sys

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import pickle
import time
from config import settings
import random


class Admin(object):
    '''封装管理员的相关功能

    '''

    def __init__(self):
        self.username = None
        self.passwd = None
        self.create_time = None

    def login(self, user, pwd):
        if self.username == user and self.passwd == pwd:
            return True
        else:
            return False

    def register(self, user, pwd):
        '''管理员注册

        :param user:
        :param pwd:
        :return:None
        '''
        self.username = user
        self.passwd = pwd
        self.create_time = time.strftime('%Y-%m-%d %H:%M:%S')

        path = os.path.join(settings.BASE_ADMIN_DIR, user)
        pickle.dump(self, open(path, 'wb'))


class Teacher(object):
    '''
    封装老师相关信息
    '''

    def __init__(self, name, sex, age, create_admin, asset=0):
        self.name = name
        if sex in ('male', 'female'):
            self.sex = sex
        self.age = age
        self.asset = asset
        self.create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        self.create_admin = create_admin

    def lose_asset(self, account):
        '''
        减少老师资产
        :param account:
        :return:
        '''
        self.asset -= account
        return self.asset

    def gain_asset(self, account):
        '''
        增加资产
        :param account:
        :return:
        '''
        self.asset += account
        list2 = []
        t_list = pickle.load(open(settings.TEACHER_DB_DIR,'rb'))
        for t in t_list:
            if t.name == self.name:
                t = self
            list2.append(t)
        pickle.dump(list2,open(settings.TEACHER_DB_DIR,'wb'))
        return self.asset


class Course(object):
    '''
    封装课程的相关信息
    '''

    def __init__(self, name, cost, teacher_obj, create_admin):
        self.course_name = name
        self.cost = cost
        self.teacher = teacher_obj
        self.create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        self.create_admin = create_admin

    def have_lesson(self):
        '''
        课程上课,自动给相关联的任课老师增加资产
        :return: 课程内容返回给上课者
        '''
        self.teacher.gain_asset(self.cost)
        content = random.randrange(10, 100)
        r = time.strftime('%Y-%m-%d %H:%M:%S')
        temp = '课程:%s,老师:%s,内容:%s,时间:%s' % (self.course_name, self.teacher.name, content, r)
        return temp

    def absence(self):
        '''
        教学事故
        :return:
        '''
        self.teacher.lose_asset(self.cost * 2)


class Student(object):
    '''
    封装学生相关信息
    '''

    def __init__(self):
        self.username = None
        self.passwd = None
        self.course_list = set()
        self.study_dict = {}
        self.total_fee = 0

    def select_course(self, course_obj):
        '''
        学生选课
        :param course:
        :return:
        '''
        self.course_list.add(course_obj)


    def study(self, course_obj):
        '''
        学生上课
        :param course_obj:
        :return:
        '''
        class_result = course_obj.have_lesson()
        self.total_fee += course_obj.cost
        if course_obj in self.study_dict.keys():
            self.study_dict[course_obj].append(class_result)
        else:
            self.study_dict[course_obj] = [class_result, ]


    def login(self, user, pwd):
        if self.username == user and self.passwd == pwd:
            return True
        else:
            return False

    def register(self, user, pwd):
        self.username = user
        self.passwd = pwd

        path = os.path.join(settings.STUDENTS_DB_DIR, user)
        pickle.dump(self, open(path, 'wb'))

2. 配置文件setting.py


import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_ADMIN_DIR= os.path.join(BASE_DIR,'db','admin')
TEACHER_DB_DIR = os.path.join(BASE_DIR,'db','teacher_list')
COURSE_DB_DIR= os.path.join(BASE_DIR,'db','course_list')
STUDENTS_DB_DIR= os.path.join(BASE_DIR,'db','students')

3. administrator.py

import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from config import settings
from lib.models import *
import pickle


def create_teacher(admin_obj):
    teacher_list = []
    while True:
        teacher_name = input("enter teacher's name(q to quit):>>> ").strip()
        if teacher_name.lower() == 'q':
            break
        teacher_sex = input('teacher sex:>>>').strip()
        teacher_age = int(input('teacher age:>>>').strip())
        teacher_obj = Teacher(teacher_name, teacher_sex,teacher_age, admin_obj)
        teacher_list.append(teacher_obj)
    if os.path.exists(settings.TEACHER_DB_DIR):
        list1 = pickle.load(open(settings.TEACHER_DB_DIR, 'rb'))
        teacher_list.extend(list1)
    pickle.dump(teacher_list, open(settings.TEACHER_DB_DIR, 'wb'))


def create_course(admin_obj):
    course_list = []
    teacher_list = pickle.load(open(settings.TEACHER_DB_DIR, 'rb'))
    for k, i in enumerate(teacher_list, 1):
        print(k, i.name, i.sex, i.age, i.create_admin, i.create_time)
    while True:
        course_name = input('course name(q to quit):>>>').strip()
        if course_name.lower() == 'q':
            break
        cost = int(input('course cost:>>>').strip())
        teacher_obj = teacher_list[int(input('teacher number:>>>').strip()) - 1]
        course_obj = Course(course_name, cost, teacher_obj, admin_obj)
        course_list.append(course_obj)
    if os.path.exists(settings.COURSE_DB_DIR):
        list2 = pickle.load(open(settings.COURSE_DB_DIR, 'rb'))
        course_list.extend(list2)
    pickle.dump(course_list, open(settings.COURSE_DB_DIR, 'wb'))


def check_tinfo(admin_obj):
    if os.path.exists(settings.TEACHER_DB_DIR):
        t_list = pickle.load(open(settings.TEACHER_DB_DIR, 'rb'))
        inp = input('请输入要查看的老师名字:>>>')
        for i in range(len(t_list)):
            if t_list[i].name == inp:
                # sex, age, create_admin, asset = 0
                print(t_list[i].name, t_list[i].age, t_list[i].create_admin.username, t_list[i].create_time, t_list[i].asset)
                return True


def check_sinfo(admin_obj):
    if os.path.exists(os.path.join(settings.STUDENTS_DB_DIR, 'xiao li')):
        stu_obj = pickle.load(open(os.path.join(settings.STUDENTS_DB_DIR, 'xiao li'), 'rb'))
        print(stu_obj.username, stu_obj.course_list, stu_obj.study_dict, stu_obj.total_fee)


def login(user, pwd):
    path = os.path.join(settings.BASE_ADMIN_DIR, user)
    if os.path.exists(path):
        admin_obj = pickle.load(open(path, 'rb'))
        if admin_obj.login(user, pwd):
            print('登陆成功')
            while True:
                inp = input('1:创建老师;2:创建课程(q退出);3:查看老师信息;4:查看学生信息:\n>>>')
                if inp == '1':
                    create_teacher(admin_obj)
                elif inp == '2':
                    create_course(admin_obj)
                elif inp == '3':
                    check_tinfo(admin_obj)
                elif inp == '4':
                    check_sinfo(admin_obj)
                else:
                    break
        else:

            return 1
    else:

        return 0


def register(user, pwd):
    admin_obj = Admin()
    admin_obj.register(user, pwd)


def main():
    print('welcome to the course system')
    inp = input('1:管理员登陆;2:管理员注册(q退出)\n:>>>').strip()
    user = input('enter username:>>>').strip()
    pwd = input('enter password:>>>').strip()

    if inp == '1':
        ret = login(user, pwd)
        if ret == '1':
            print('密码错误')
        elif ret == '0':
            print('没有此用户,请先注册')
    elif inp == '2':
        register(user, pwd)
    elif inp == 'q':
        exit()
    else:
        print('输入非法,请重新输入')


if __name__ == '__main__':
    main()

4. student.py

import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from config import settings
from lib.models import *
import pickle


def check_cinfo(stu_obj):
    course_list = stu_obj.course_list
    print('%s %s %s %s ' % ('序号', '名称', '费用', '老师'))
    for k, v in enumerate(course_list, 1):
        print(k, v.course_name, v.cost, v.teacher.name)


def select_course(stu_obj):
    if os.path.exists(settings.COURSE_DB_DIR):
        course_list = pickle.load(open(settings.COURSE_DB_DIR, 'rb'))
        for k, v in enumerate(course_list, 1):
            print(k, v.course_name, v.cost, v.teacher.name)
        while True:
            inp = (input('请输入课程序列号进行选课:>>>').strip())
            if inp == 'q':
                break
            stu_obj.select_course(course_list[int(inp) - 1])
        path = os.path.join(settings.STUDENTS_DB_DIR, stu_obj.username)
        pickle.dump(stu_obj, open(path, 'wb'))


def study(stu_obj):
    if stu_obj.course_list:
        for k, v in enumerate(list(stu_obj.course_list), 1):
            print(k, v.course_name,v.teacher.name)
        while True:
            inp = (input('请输入课程序列号进行上课:>>>').strip())
            if inp == 'q':
                break
            stu_obj.study(list(stu_obj.course_list)[int(inp) - 1])
    path = os.path.join(settings.STUDENTS_DB_DIR, stu_obj.username)
    pickle.dump(stu_obj, open(path, 'wb'))



def login(user, pwd):
    if os.path.exists(os.path.join(settings.STUDENTS_DB_DIR, user)):
        stu_obj = pickle.load(open(os.path.join(settings.STUDENTS_DB_DIR, user), 'rb'))
        if stu_obj.login(user, pwd):
            print('登录成功')
            while True:
                inp = input('1:选课;2:上课,3:查看课程信息:(q to quit);\n:>>>').strip()
                if inp == '1':
                    select_course(stu_obj)
                elif inp == '2':
                    study(stu_obj)
                elif inp == '3':
                    check_cinfo(stu_obj)
                else:
                    break

        else:
            return 1
    else:
        return 0


def register(user, pwd):
    student = Student()
    student.register(user, pwd)


def main():
    inp = input('1:学生登录;2:学生注册(q退出)\n:>>>').strip()
    user = input('enter name:>>>').strip()
    pwd = input('enter password:>>>').strip()
    if inp == '1':
        login(user, pwd)
    elif inp == '2':
        register(user, pwd)
    else:
        exit()


if __name__ == '__main__':
    main()

猜你喜欢

转载自www.cnblogs.com/lanxing0422/p/pythonday12.html