ジョブ21

1.对象有id、host、port三个属性
2.定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一  
3.提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化  
4.为对象定制方法,save和get_obj_by_id,save能自动将对象序列化到文件中,文件路径为配置文件中DB_PATH,文件名为id号,保存之前验证对象是否已经存在,若存在则抛出异常,;get_obj_by_id方法用来从文件中反序列化出对象

HOST='127.0.0.1'
PORT=3306
DB_PATH=r'E:\CMS\aaa\db'
'''
from conf import settings
import uuid
import pickle
import os
class MySQL:
    def __init__(self,host,port):
        self.id=self.create_id()
        self.host=host
        self.port=port

    def save(self):
        if not self.is_exists:
            raise PermissionError('对象已存在')
        file_path=r'%s%s%s' %(settings.DB_PATH,os.sep,self.id)
        pickle.dump(self,open(file_path,'wb'))

    @property
    def is_exists(self):
        tag=True
        files=os.listdir(settings.DB_PATH)
        for file in files:
            file_abspath=r'%s%s%s' %(settings.DB_PATH,os.sep,file)
            obj=pickle.load(open(file_abspath,'rb'))
            if self.host == obj.host and self.port == obj.port:
                tag=False
                break
        return tag
    @staticmethod
    def get_obj_by_id(id):
        file_abspath = r'%s%s%s' % (settings.DB_PATH, os.sep, id)
        return pickle.load(open(file_abspath,'rb'))

    @staticmethod
    def create_id():
        return str(uuid.uuid1())

    @classmethod
    def from_conf(cls):
        print(cls)
        return cls(settings.HOST,settings.PORT)

# print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>>
conn=MySQL.from_conf()
conn.save()

conn1=MySQL('127.0.0.1',3306)
conn1.save() #抛出异常PermissionError: 对象已存在


obj=MySQL.get_obj_by_id('7e6c5ec0-7e9f-11e7-9acc-408d5c2f84ca')
print(obj.host)
2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
        参考答案(http://www.cnblogs.com/linhaifeng/articles/7340801.html#_label4)
import math


class Circle:
    def __init__(self, r):
        self.__r = r

    @property
    def area(self):
        return math.pi * self.__r ** 2

    @property
    def perimeter(self):
        return 2 * math.pi * self.__r

    @property
    def get_r(self):
        return self.__r


c = Circle(10)
print(c.get_r)
print(c.area)
print(c.perimeter)
3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类'''

import abc #利用abc模块实现抽象类

class Phone(metaclass=abc.ABCMeta):
    @abc.abstractmethod #定义抽象方法,无需实现功能
    def phone_name(self):
        pass

    @abc.abstractmethod #定义抽象方法,无需实现功能
    def phone_price(self):
        '子类必须定义写功能'
        pass

class iPhone(Phone): #子类继承抽象类,但是必须定义方法
    def phone_name(self):
        print('苹果手机 11')

    def phone_price(self):
        print('价格一万')


class huawei(Phone): #子类继承抽象类,但是必须定义方法
    def phone_name(self):
        print('华为手机 pr30')
    def phone_price(self):
        print('价格两万')

i1 = iPhone()
h1 = huawei()

i1.phone_name()
h1.phone_name()
i1.phone_price()
h1.phone_price()
4、着手编写选课系统作业

'''直接运行即可,注意细节'''
'''注意管理员为自动创建,user=admin, pass=123,直接登录即可'''

import os
import json


class User:
    def __init__(self, name):  # 传入用户名
        self.name = name

    dic = {"查看课程": 'User_see', '选择课程': 'Choice_course', "查看所选课程": 'Selected', "退出": 'Exit'}

    def User_see(self):  # 查看所有课程
        with open('class_all.txt', encoding='utf-8') as file:
            tmp = {}  # 通过字典添加值
            for index, i in enumerate(file.read().split('|')[:-1], 1):
                print(index, i)
                tmp.setdefault(str(index), i)  # 把得到的结果放入到tmp中
            return tmp  # 把返回值return出去

    def Choice_course(self):  # 选择课程
        tmp = self.User_see()  # 调用查看课程的方法显示
        Choice = input('请输入你选择的课程序号')
        if Choice in tmp:  # 判断选的课在不在列表里
            with open('choice_class.txt', encoding='utf-8') as file:
                chice_class = json.load(file)  # 把chice_class.txt序列化出来,得到字典
                if chice_class.get(self.name):  # 判断用户和课程里有没有那个用户
                    chice_class.get(self.name).append(tmp[Choice])  # 添加到字典中
                else:
                    chice_class.setdefault(self.name, [tmp[Choice]])
            with open('choice_class.txt', encoding='utf-8', mode='w') as file:
                json.dump(chice_class, file, ensure_ascii=False)  # 再把chice_class值放入到文件中
        else:
            print('不在范围内')

    def Selected(self):  # 查看所选课程
        with open('choice_class.txt', encoding='utf-8') as file:
            user_course = json.load(file)  # 把chice_class.txt序列化出来,得到字典
            print(user_course.get(self.name))

    def Exit(self):  # 退出
        exit('欢迎下次再来。。。')


class Admin:
    dic = {"创建课程": 'Create_course', '创建学生学生账号': 'Create_user',
           "创建讲师账号": 'Create_teacher', "为讲师指定班级": "Appoint_class",
           "为学生指定班级": "Student_class", "查看所有课程": 'Select_all_course',
           "创建班级": "Create_class", "查看所有学生": 'Select_user_all',
           "查看所有学生的选课情况": 'Select_course_user', '退出程序': 'Exit'}

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

    def Create_course(self):  # 创建课程
        Choice = input('输入创建课程名称')
        with open('class_all.txt', encoding='utf-8', mode='a') as file:
            file.write(Choice + '|')
        print('创建{}课程成功'.format(Choice))

    def Create_user(self):  # 创建学生账号
        stu_name = input('请输入学生账号:').strip()
        stu_pwd = input('请输入学生密码:').strip()
        with open('user.txt', encoding='utf-8', mode='a') as file:
            file.write('\n{}|{}|student'.format(stu_name, stu_pwd))
        print('{}同学创建成功'.format(stu_name))

    def Create_teacher(self):  # 创建讲师账号
        stu_name = input('请输入讲师账号:').strip()
        stu_pwd = input('请输入讲师密码:').strip()
        with open('user.txt', encoding='utf-8', mode='a') as file:
            file.write('\n{}|{}|Teacher'.format(stu_name, stu_pwd))
        with open('teacher.txt', encoding='utf-8', mode='a') as file:  # 创建完成后把name写入teacher.txt文件中
            file.write(stu_name + '|')
        print('{}讲师创建成功'.format(stu_name))

    def Appoint_class(self):  # 为讲师指定班级
        with open('Create_class.txt', encoding='utf-8') as file:
            p1 = json.load(file)  # 把班级文件序列化出来
        tmp1 = []
        if os.path.exists('teacher.txt'):  # 判断文件是否存在
            with open('teacher.txt', encoding='utf-8', mode='r') as file:
                for i in file.readlines():
                    tmp1 = i.strip().split('|')[:-1]  # 把值添加到tmp1列表中
            for i, index in enumerate(tmp1, 1):  # 显示老师名称
                print(i, index)
            for i, index in enumerate(p1, 1):  # 显示班级名称
                print(i, index)
            choice_tracher = int(input('输入你选择的讲师')) - 1
            with open('teacher_class.txt', encoding='utf-8', mode='r') as file:
                l1 = json.load(file)
            if p1 == []:  # 判断是否有班级存在
                print('如果要添加则请先创建班级')
            else:
                choice_class = int(input('输入你选择的班级')) - 1
                if l1.get(tmp1[choice_tracher]):  # 判断l1字典中是否为新用户
                    l1.get(tmp1[choice_tracher]).append(p1[choice_class])  # 追加到后面list中
                else:
                    l1.setdefault(tmp1[choice_tracher], [p1[choice_class]])  # 单个key value
                l1[tmp1[choice_tracher]] = list(set(l1[tmp1[choice_tracher]]))  # 去重
                with open('teacher_class.txt', encoding='utf-8', mode='w') as file:
                    json.dump(l1, file, ensure_ascii=False)  # 写入文件
                print('{}老师指定{}成功'.format(tmp1[choice_tracher], p1[choice_class]))
        else:
            print('清先创建讲师')

    def Student_class(self):  # 为学生指定班级
        p1 = self.Select_user_all()  # 调用Select_user_all方法,查看出有哪些学生,p1为列表
        if p1 == []:  # 是否有学生存在
            print('清先创建学生后在来添加')
        else:
            if os.path.exists('Create_class.txt'):
                print('所有班级为:')
                with open('Create_class.txt', encoding='utf-8') as file:
                    tmp1 = json.load(file)
                    for i, index in enumerate(tmp1, 1):
                        print(i, index)
                user = int(input('输入你添加的学生序号')) - 1
                student = int(input('输入你添加的班级序号')) - 1
                with open('student_class.txt', encoding='utf-8', mode='r') as file:
                    l1 = json.load(file)

                if l1.get(tmp1[student]):  # 判断l1中key是否有此用户
                    l1.get(tmp1[student]).append(p1[user])
                else:
                    l1.setdefault(tmp1[student], [p1[user]])
                l1[tmp1[student]] = list(set(l1[tmp1[student]]))  # 去重
                with open('student_class.txt', encoding='utf-8', mode='w') as file:
                    json.dump(l1, file, ensure_ascii=False)
                print('{}添加{}学生成功'.format(tmp1[student], p1[user]))

            else:
                print('请先创建班级后再来添加')

    def Create_class(self):  # 创建班级
        Test_class = input('输入你创建班级的名称如(-年级-班)')
        if os.path.exists('Create_class.txt'):  # 判断文件是否存在
            with open('Create_class.txt', encoding='utf-8') as file:
                p1 = json.load(file)
                p1.append(Test_class)  # 添加班级

        else:
            with open('Create_class.txt', encoding='utf-8', mode='w') as file:
                file.write('[]')  # 创建文件,添加 []
            with open('Create_class.txt', encoding='utf-8') as file:
                p1 = json.load(file)
                p1.append(Test_class)

        with open('Create_class.txt', encoding='utf-8', mode='w') as file:
            json.dump(p1, file, ensure_ascii=False)  # 写入文件
        print('创建{}成功'.format(Test_class))
        return p1  # 把列表返回出去

    def Select_all_course(self):  # 查看所有课程
        print('查看的课程为')
        with open('class_all.txt', encoding='utf-8') as f:
            tmp = {}
            for index, i in enumerate(f.read().split('|')[:-1], 1):
                print(index, i, )
                tmp.setdefault(str(index), i)
            return tmp  # 方便后面方法使用

    def Select_user_all(self):  # 查看所有学生
        student = []
        with open('user.txt', encoding='utf-8') as file:
            print('学生用户为:')
            for i, index in enumerate(file.readlines()):
                if index.strip().split('|')[-1] == 'student':  # 取出学生
                    print(i, index.strip().split('|')[0])
                    student.append(index.strip().split('|')[0])
        return student

    def Select_course_user(self):  # 查看所有学生的选课情况
        if os.path.exists('choice_class.txt'):
            with open('choice_class.txt', encoding='utf-8') as file:
                for i in file.readlines():  # 列出文件的每行类容
                    print(i)
        else:
            print('清先登录学生账号添加课程后查看')

    def Exit(self):  # 退出
        exit('欢迎下次再来。。。')


class Teacher:
    def __init__(self, name):
        self.name = name

    dic = {'查看所有课程': 'Select_choice', '查看所教班级': 'Select_student',
           '查看班级中的学生': 'Select_class_student', '退出': 'Exit'}

    def Select_choice(self):  # 查看所有课程
        if os.path.exists('class_all.txt'):  # 判断课程是否存在
            with open('class_all.txt', encoding='utf-8') as file:
                for i in file.readlines():
                    print(i.strip().split('|')[:-1])

        else:
            print('请先登录管理员创建课程')

    def Select_student(self):  # 查看所教班级
        if os.path.exists('teacher_class.txt'):
            with open('teacher_class.txt', encoding='utf-8') as file:
                tmp1 = json.load(file).get(self.name)
                print(tmp1)
                return tmp1
        else:
            print('目前暂无,请登录管理员添加')

    def Select_class_student(self):  # 查看班级中的学生
        if os.path.exists('teacher_class.txt') and os.path.exists('student_class.txt'):
            tmp = self.Select_student()  # 先调用Select_student方法查看,tmp得到返回值
            with open('student_class.txt', encoding='utf-8') as file:
                student = json.load(file)
            if tmp == None:
                print('当前老师班级没有学生')
            else:
                for i in tmp:
                    if student.get(i):
                        print(i, student[i])

        else:
            print('目前暂无,请登录管理员添加')

    def Exit(self):  # 退出
        exit('欢迎下次再来。。。')


class login_Test:  # 判断登录账户
    print('欢迎来到学员管理系统')

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def login(self):
        with open('user.txt', encoding='utf-8') as file:
            for i in file.readlines(): # 取出每一行
                '''判断用户密码是否正确'''
                if self.username == i.strip().split('|')[0] and self.password == i.strip().split('|')[1]:
                    if i.strip().split('|')[-1] == 'admin':
                        return 'admin'
                    elif i.strip().split('|')[-1] == 'student':
                        return 'student'
                    elif i.strip().split('|')[-1] == 'Teacher':
                        return 'teacher'
            else:
                print('用户名密码错误')


def log_status():  # 方便后面调用
    tmp = []
    username = input('请输入用户名')
    password = input('请输入密码')
    p1 = login_Test(username, password)
    tmp.append(username)
    tmp.append(p1.login())
    return tmp


def func(class_func):
    tmp = {}
    while 1:
        for index, i in enumerate(class_func.dic, 1):
            print(index, i)
            tmp.setdefault(str(index), class_func.dic[i])
        p2 = input("输入你选择的序号")
        getattr(class_func, tmp[p2])()

'''用于文件创建'''
if os.path.exists('user.txt') == False:
    with open('user.txt', encoding='utf-8', mode='w') as file:
        file.write('admin|123|admin')
if os.path.exists('teacher_class.txt') == False:
    with open('teacher_class.txt', encoding='utf-8', mode='w') as file:
        file.write('{}')
if os.path.exists('choice_class.txt') == False:
    with open('choice_class.txt', encoding='utf-8', mode='w') as file:
        file.write('{}')
if os.path.exists('Create_class.txt') == False:
    with open('Create_class.txt', encoding='utf-8', mode='w') as file:
        file.write('[]')
if os.path.exists('class_all.txt') == False:
    with open('class_all.txt', encoding='utf-8', mode='w') as file:
        pass
if os.path.exists('student_class.txt') == False:
    with open('student_class.txt', encoding='utf-8', mode='w') as file:
        file.write('{}')
login_status = log_status()  # class_all.txt
while True:
    if login_status[1] == 'student':
        p1 = User(login_status[0])
        func(p1)

    elif login_status[1] == 'admin':
        p1 = Admin(login_status[0])
        func(p1)
    elif login_status[1] == 'teacher':
        p1 = Teacher(login_status[0])
        func(p1)
    else:
        break

おすすめ

転載: www.cnblogs.com/gfhh/p/11655988.html
おすすめ