NO.6:自学python之路------面向对象、内存持久…

2018-07-09 13:28:30来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

引言

  虽然加速学习了,可是还是感觉进度不够快,担心。还得准备毕业论文,真是焦虑。

正文

面向对象

  编程是程序员用特定语法+数据结构+算法组成的代码,告诉计算机如何执行任务的过程。对不同的编程方式的特点进行归纳总结得出的编程方式类别即为编程范式。常见的编程范式有面向过程编程、面向对象编程和函数式编程。

  面向过程(Procedure Oriented)是一种以过程为中心的编程思想。面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了。但是,如果需要修改代码,与其有依赖的各个部分也需要修改。维护难度高。所以通常应用于一次性的任务。

  函数式编程(Functional programming)属于"结构化编程"的一种,主要思想是把运算过程尽量写成一系列嵌套的函数调用。虽然也可以归结到面向过程的程序设计,但其思想更接近数学计算。

  面向对象(Object Oriented)是一种提供符号设计系统的面向对象的实现过程,它用非常接近实际领域术语的方法把系统构造成“现实世界”的对象。它利用类和对象创建各种模型实现对真实世界的描述。它具有维护和扩展变得简单,可以使其他人更加容易理解代码逻辑的特点。

  用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。Python中类的定义有两种,一种是新式类,一种是传统类。他们的区别主要体现在继承中。例子。

class test(object):#新式类
    '''类的描述'''
    #具体内容
class test():#传统类
    '''类的描述'''
    #具体内容

对象

  通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。例子。

class test(object):#新式类
    '''类的描述'''
    pass

a = test#实例化,对象

封装

  类中对数据的赋值,使类变成一个胶囊或容器,里面包含有类的数据和方法。例子。

class test(object):#新式类
    '''类的描述'''
    def __init__(self,name):
        self.name = name
    def info(self):
        print(self.name)

a = test('王二蛋')#实例化,对象 
a.name #封装
a.info()

继承

  类可以派生出子类,父类里的属性和方法被子类自动继承。对于互相继承的类A、B、C、D,按先后,B继承A,C继承A,D继承B,D继承C.在Python3中或着是Python2的新式类中:D依次从B、C、A中继承构造函数,继承到一个以后就停止。即,广度优先,横向查询后向上。Python2的经典类中,D依次从B、A、C中继承构造函数,继承到一个以后就停止。即,深度优先。例子。

class test(object):#新式类
    '''类的描述'''
    def __init__(self,name):
        self.name = name
    def info(self):
        print(self.name)

class new(test):#继承
    def new_func(self):
        print('%s is using new function'%(self.name))

a = new('王二蛋')#实例化,对象 
a.name #封装
a.info()
a.new_func()
View Code

多态性

  简单说,多态性就是一个接口,多种实现。例子。

class Animal(object):
    """description of class"""
    def __init__(self,name):
        #构造函数
        self.name = name#实例变量(静态属性),作用在实例本身

    @staticmethod
    def new_eat(obj):
        obj.eat()

class Cat(Animal):
    def eat(self):
        print('猫粮')
class Dog(Animal):
    def eat(self):
        print('狗粮')
cat = cat('喵喵')
dog = dog('汪汪')
cat.eat()#分别调用
Animal.new_eat(cat)#统一接口
View Code

语法

  函数过程:调用函数->函数执行->返回结果

  对象过程:开辟类->开辟对象->对象传入类赋值

  类中的self用于接收对象名。一个较为完整的类的结构如下所示。

class test(object):#类名
    """description of class"""
    name = 111#类变量,无法被实例化对象修改
    def __init__(self,name):
        #构造函数
        #作用:在实例化时做一些类的初始化的工作
        self.name = name#实例变量(静态属性),作用在实例本身
        self.__test = 'person'#私有属性

    def test(self):
        #类的方法(动态属性)
        print('%s say hello'%self.name)

    def __del__(self):
        #析构函数
        #作用:在类销毁时执行一些操作
        print('对象已销毁!')

内存持久化

  因为内存数据不能持久保存,所以经常需要将内存中的数据保存到本地,方便程序下次运行时使用。前面已经介绍过几种。对于类的持久化,在Python中也有非常简便的模块。

shelve

import shelve#内存数据持久化模块
class test(object):
    def __init__(self,n):
        self.n = n
t = test(123)
a = ['aa','bb','cc']
d = shelve.open('test')
d['name1'] = a #持久化列表
d['name2'] = t #持久化类
d.close()#保存关闭

f = shelve.open('test')
print(f.get['name1'])#读取
View Code

作业

  实现一个学校教师学生办公系统。

要求:

  1.自动创建2所学校。

  2.管理界面:可以创建讲师,班级,课程。

  3.教师界面:上课选择班级,查看学员列表,修改学员成绩。

  4.学生界面:可以注册,交学费,选班级。

  5.课程包含周期,价格,课程通过学校创建。

  6.班级通过学校创建,关联课程和讲师。创建学员时,选择学校,关联班级。创建讲师角色时关联学校。

  7.数据都通过序列化保存

文件目录

-bin\

  __init__.py

  STS.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#root directory
sys.path.append(BASE_DIR)

from core import main

if __name__ == '__main__':
    '''open in the right way'''
    main.run()
STS.py

-conf\

  __init__.py

  setting.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

ADMIN_DATA = {
    'type': 'dat',
    'name': 'admin',
    'path': r'%s\database' % BASE_DIR,
    }
setting.py

-core\

  __init__.py

  admin_sys.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

import os
import sys

from core.db_handle import DataBase
from conf.setting import *
from src.school import School
from src.catelog import Catelog

admin_db = DataBase(ADMIN_DATA)

admin_dic = {'1':['讲师相关','add_teacher'],
             '2':['班级相关','add_grade'],
             '3':['课程相关','add_course'],
             'b':['返回','break_sys'],
             'q':['退出','exit_sys'],
             }

class Admin_sys(object):
    '''admin system'''
    def __init__(self):
        self.select = []
        self.option = 0
        if admin_db.db_exist():
            self.admin = admin_db.shelve_open()
        else:
            print('初次打开正在初始化')
            self.__init_school()
        self.interactive(admin_dic)

    def __init_school(self):
        self.admin = []
        self.admin.append(School('华电','北京'))
        self.admin.append(School('华电','保定'))
        admin_db.shelve_write(self.admin)

    def add_teacher(self):
        teacher_name = input('请输入讲师姓名>>')
        if teacher_name in self.select.teacher:
            self.select.teacher_info[teacher_name].info()
            option = input('讲师名称已存在,是否修改[Y/N]>>')
            if option == 'Y' or option == 'y':
                teacher_grade = input('请输入讲师班级>>')
                if teacher_grade in self.select.grade:
                    teacher_age = input('请输入讲师年龄>>')
                    teacher_sex = input('请输入讲师性别>>')
                    teacher_salary = input('请输入讲师薪水>>')
                    self.select.creat_teacher(teacher_name,teacher_age,teacher_sex,teacher_salary,teacher_grade)
                    self.update()
                else:
                    option = input('班级不存在,是否创建班级[Y/N]>>')
                    if option == 'Y' or option == 'y':
                        self.add_grade()
                    else:
                        print('修改取消')
            else:
                print('创建取消')
        else:
            option = input('讲师名称不存在,是否创建[Y/N]>>')
            if option == 'Y' or option == 'y':
                teacher_grade = input('请输入讲师班级>>')
                if teacher_grade in self.select.grade:
                    teacher_age = input('请输入讲师年龄>>')
                    teacher_sex = input('请输入讲师性别>>')
                    teacher_salary = input('请输入讲师薪水>>')
                    self.select.creat_teacher(teacher_name,teacher_age,teacher_sex,teacher_salary,teacher_grade)
                    self.update()
                else:
                    option = input('班级不存在,是否创建班级[Y/N]>>')
                    if option == 'Y' or option == 'y':
                        self.add_grade()
                    else:
                        print('创建取消')
            else:
                print('创建取消')
    def add_grade(self):
        grade_name = input('请输入班级名称>>')
        if grade_name in self.select.grade:
            print('%s班 课程:%s'%(grade_name,self.select.grade_info[grade_name].course))
            option = input('班级已存在,是否修改[Y/N]>>')
            if option == 'Y' or option == 'y':
                grade_course = input('请输入班级课程>>')
                if grade_course in self.select.course:
                    self.select.creat_grade(grade_name,grade_course)
                    self.update()
            else:
                print('创建取消')
        else:
            option = input('班级不存在,是否创建[Y/N]>>')
            if option == 'Y' or option == 'y':
                grade_course = input('请输入班级课程>>')
                if grade_course in self.select.course:
                    self.select.creat_grade(grade_name,grade_course)
                    self.update()
                else:
                    option = input('课程不存在,是否创建课程[Y/N]>>')
                    if option == 'Y' or option == 'y':
                        self.add_course()
                    else:
                        print('创建取消')
            else:
                print('创建取消')

    def add_course(self):
        course_name = input('请输入课程名称>>')
        if course_name in self.select.course:
            print('%s 价格:%s 课时:%s周'%(course_name,self.select.course_info[course_name].price,self.select.course_info[course_name].time))
            option = input('课程已存在,是否修改[Y/N]>>')
            if option == 'Y' or option == 'y':
                course_price = input('请输入课程价格>>')
                course_time = input('请输入课时总量>>')
                self.select.creat_course(course_name,course_price,course_time)
                self.update()
            else:
                print('创建取消')
        else:
            print('课程不存在,正在创建')
            course_price = input('请输入课程价格>>')
            course_time = input('请输入课时总量>>')
            self.select.creat_course(course_name,course_price,course_time)
            self.update()

    def interactive(self,menu_dic):
        select_flag = True
        while select_flag:
            num = 1
            for i in self.admin:
                print('%d. %s 地址:%s'%(num,i.name,i.address))
                num = num + 1
            option = input('请输入管理学校序号>>')
            if option.isdigit() and int(option) >= 1 and int(option) < num:
                self.option = int(option)-1
                self.select = self.admin[self.option]
                select_flag = False
            else:
                print('输入错误')
        print('欢迎来到%s学校'%(self.select.name))
        list_menu = Catelog(menu_dic)
        interac_flag = True
        while interac_flag:
            list_menu.menu_print()
            option = list_menu.menu_select()
            if option == 'break_sys':
                interac_flag = False
            elif option is not None:
                getattr(self,option)()
    
    def update(self):
        self.admin[self.option] = self.select
        admin_db.shelve_write(self.admin)
    
    def exit_sys(self):
        print('程序退出!')
        sys.exit(0)
admin_sys.py

  db_handle.py

#-*- coding:utf-8 -*-
#author: Kai Zhang
import os
import shelve

from conf import setting

class DataBase(object):
    def __init__(self,data_param):
        self.path = data_param['path']
        self.name = data_param['name']
        self.type = data_param['type']
        self.file = r'%s\%s'%(self.path,self.name)
        self.adbpath = r'%s\%s.%s'%(self.path,self.name,self.type)

    def db_exist(self):
        '''
        file exist judgment
        '''
        return os.path.exists(self.adbpath)

    def shelve_open(self):
        file = shelve.open(self.file)
        data = file.get('data')
        file.close()
        print('读取成功')
        return data

    def shelve_write(self,data):
        file = shelve.open(self.file)
        file['data'] = data
        file.close()
        print('保存成功')
db_handle.py

  main.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

import sys

from src import catelog
from core.admin_sys import Admin_sys
from core.teacher_sys import Teacher_sys
from core.student_sys import Student_sys

main_dic = {'1':['学生系统','Student_sys'],
            '2':['教师系统','Teacher_sys'],
            '3':['管理系统','Admin_sys'],
            'q':['退出系统','exit_sys'],
            }

def exit_sys():
    '''exit system'''
    print('程序退出!')
    sys.exit(0)

def interactive(list_obj):
    '''
    interact with user
    return:None
    '''
    interac_flag = True
    while interac_flag:
        list_obj.menu_print()
        option = list_obj.menu_select()
        if option == 'break_sys':
            interac_flag = False
        elif option is not None:
            exec('%s()'%(option))
        
def run():
    '''start the program'''
    list_main = catelog.Catelog(main_dic)
    interactive(list_main)
main.py

  student_sys.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

import os
import sys

from core.db_handle import DataBase
from conf.setting import *
from src.school import School
from src.catelog import Catelog

admin_db = DataBase(ADMIN_DATA)

student_dic = {'1':['注册学籍','regist_statu'],
               '2':['报名课程','select_grade'],
               'b':['返回','break_sys'],
               'q':['退出','exit_sys'],
               }

class Student_sys(object):
    '''student system'''
    def __init__(self):
        self.select = []
        self.option = 0
        self.grade = []
        self.student = []
        self.student_name = ''
        if admin_db.db_exist():
            self.admin = admin_db.shelve_open()
            self.interactive(student_dic)
        else:
            print('系统没有信息,请进入管理系统维护')

    def select_grade(self):
        if self.student_name in self.select.student:
            grade_name = input('请输入您想报名的班级>>')
            if grade_name in self.select.grade:
                self.grade = self.select.grade_info[grade_name]
                if self.student_name in self.grade.student:
                    print('你已报名该班级!')
                    self.student = self.grade.student_info[self.student_name]
                    print('%s 年龄:%s 性别:%s 班级:%s 分数:%s'%(self.student.name,self.student.age,self.student.sex,self.student.grade,self.student.score))
                else:
                    money = int(input('你需要缴纳学费%s元,请输入现金>>'%(self.select.course_info[self.grade.student_info[self.student_name].course].price)))
                    if money >= int(self.select.course_info[self.grade.student_info[self.student_name].course].price):
                        print('缴费成功,找零%s'%(money - int(self.select.course_info[self.grade.student_info[self.student_name].course].price)))
                        self.select.select_grade(grade_name,self.student_name)
                        self.student = self.grade.student_info[self.student_name]
                        print('%s 年龄:%s 性别:%s 班级:%s 分数:%s'%(self.student.name,self.student.age,self.student.sex,self.student.grade,self.student.score))
                        self.update()
                    else:
                        print('缴费不足,已取消交易!')
            else:
                print('班级不存在')
        else:
            print('请先注册学籍!')

    def regist_statu(self):
        if self.student_name in self.select.student:
            print('你已注册!')
        else:
            student_age = input('请输入你的年龄>>')
            student_sex = input('请输入你的性别>>')
            self.select.creat_student(self.student_name,student_age,student_sex)
            self.update()

    def interactive(self,menu_dic):
        select_flag = True
        while select_flag:
            num = 1
            for i in self.admin:
                print('%d. %s 地址:%s'%(num,i.name,i.address))
                num = num + 1
            option = input('请输入所在学校序号>>')
            if option.isdigit() and int(option) >= 1 and int(option) < num:
                self.option = int(option)-1
                self.select = self.admin[self.option]
                select_flag = False
            else:
                print('输入错误')
        student_name = input('请输入您的姓名>>')
        self.student_name = student_name
        list_menu = Catelog(menu_dic)
        interac_flag = True
        while interac_flag:
            list_menu.menu_print()
            option = list_menu.menu_select()
            if option == 'break_sys':
                interac_flag = False
            elif option is not None:
                getattr(self,option)()

    def update(self):
        self.admin[self.option] = self.select
        admin_db.shelve_write(self.admin)     
    
    def exit_sys(self):
        print('程序退出!')
        sys.exit(0)
student_sys.py

  teacher_sys.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

import os
import sys

from core.db_handle import DataBase
from conf.setting import *
from src.school import School
from src.catelog import Catelog

admin_db = DataBase(ADMIN_DATA)

teacher_dic = {'1':['选班上课','select_class'],
               '2':['查看学生','student_info'],
               '3':['修改成绩','modify_score'],
               'b':['返回','break_sys'],
               'q':['退出','exit_sys'],
               }

class Teacher_sys(object):
    '''teacher system'''
    def __init__(self):
        self.select = []
        self.option = 0
        self.teacher = []
        self.grade = []
        self.course = []
        self.teacher_name = ''
        if admin_db.db_exist():
            self.admin = admin_db.shelve_open()
            self.interactive(teacher_dic)
        else:
            print('系统没有信息,请进入管理系统维护')

    def modify_score(self):
        student_name = input('请输入学生姓名>>')
        if student_name in self.grade.student:
            student_score = input('请输入学生分数>>')
            self.select.grade_info[self.teacher.grade].modify_score(student_name,student_score)
            self.grade = self.select.grade_info[self.teacher.grade]
            print('%s 分数:%s'%(student_name,self.grade.student_info[student_name].score))
            self.update()
        else:
            print('学生名不在班级中')
    def student_info(self):
        self.grade.grade_info()

    def select_class(self):
        print('您所教授的班级为%s,班级课程为%s,课程费用为%s,课时为%s'%(self.grade.name,self.grade.course,self.course.price,self.course.time))
        grade_name = input('请输入您想修改的班级>>')
        if grade_name in self.select.grade:
            self.select.teacher_info[self.teacher_name].change_grade(grade_name)
            self.grade = self.select.grade_info[self.teacher.grade]
            self.course = self.select.course_info[self.grade.course]
            print('您所教授的班级为%s,班级课程为%s,课程费用为%s,课时为%s'%(self.grade.name,self.grade.course,self.course.price,self.course.time))
            self.update()
        else:
            print('班级不存在,请联系管理员添加')

    def interactive(self,menu_dic):
        select_flag = True
        while select_flag:
            num = 1
            for i in self.admin:
                print('%d. %s 地址:%s'%(num,i.name,i.address))
                num = num + 1
            option = input('请输入所在学校序号>>')
            if option.isdigit() and int(option) >= 1 and int(option) < num:
                self.option = int(option)-1
                self.select = self.admin[self.option]
                select_flag = False
            else:
                print('输入错误')
        teacher_name = input('请输入您的姓名>>')
        self.teacher_name = teacher_name
        if teacher_name in self.select.teacher:
            self.select.teacher_info[teacher_name].info()
            self.teacher = self.select.teacher_info[teacher_name]
            self.grade = self.select.grade_info[self.teacher.grade]
            self.course = self.select.course_info[self.grade.course]
            list_menu = Catelog(menu_dic)
            interac_flag = True
            while interac_flag:
                list_menu.menu_print()
                option = list_menu.menu_select()
                if option == 'break_sys':
                    interac_flag = False
                elif option is not None:
                    getattr(self,option)()
        else:
            print('教师姓名不存在,请先联系管理员注册')

    def update(self):
        self.admin[self.option] = self.select
        admin_db.shelve_write(self.admin)     
    
    def exit_sys(self):
        print('程序退出!')
        sys.exit(0)
teacher_sys.py

-database\

  __init__.py

  数据文件

-src\

  __init__.py

  catelog.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

class Catelog(object):
    """catelog"""
    def __init__(self,menu_dic):
        self.menu = menu_dic#输入目录字典

    def menu_print(self):
        for i in self.menu:
            print('%s. %s'%(i,self.menu[i][0]))#打印目录字典

    def menu_select(self):
        option = input('请输入选项>>')
        if option in self.menu:
            return self.menu[option][1]#返回相关操作
        else:
            print('选项不存在!')
            return None
catelog.py

  member.py

class Member(object):
    """member of school"""
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    def info(self):
        pass

class Teacher(Member):
    def __init__(self,name,age,sex,salary,grade):
        super(Teacher,self).__init__(name,age,sex)
        self.salary = salary
        self.grade = grade

    def info(self):
        print('''%s老师 年龄:%s 性别:%s 薪水:%s 班级:%s'''%
              (self.name,self.age,self.sex,self.salary,self.grade)
              )

    def change_grade(self,grade):
        self.grade = grade
        

class Student(Member):
    def __init__(self,name,age,sex):
        super(Student,self).__init__(name,age,sex)
member.py

  school.py

#-*- coding:utf-8 -*-
#author: Kai Zhang

from src.member import Teacher
from src.member import Student

class School(object):
    def __init__(self,name,address):
        self.name = name
        self.address = address
        self.course = []
        self.course_info = {}
        self.grade = []
        self.grade_info = {}
        self.teacher = []
        self.teacher_info = {}
        self.student = []
        self.student_info = {}

    def creat_course(self,name,price,time):
        '''创建课程'''
        self.course.append(name)
        self.course_info[name] = Course(name,price,time)

    def creat_grade(self,name,course):
        '''创建班级'''
        self.grade.append(name)
        self.grade_info[name] = Grade(name,course)

    def creat_teacher(self,name,age,sex,salary,grade):
        '''创建教师'''
        self.teacher.append(name)
        self.teacher_info[name] = Teacher(name,age,sex,salary,grade)

    def creat_student(self,name,age,sex):
        '''创建学生'''
        self.student.append(name)
        self.student_info[name] = Student(name,age,sex)

    def select_grade(self,grade_name,student_name):
        '''选择学校'''
        self.grade_info[grade_name].student.append(student_name)
        self.grade_info[grade_name].student_info[student_name] = self.student_info[student_name]
        self.grade_info[grade_name].student_info[student_name].grade = grade_name
        self.grade_info[grade_name].student_info[student_name].score = 0

class Course(object):
    def __init__(self,name,price,time):
        self.name = name
        self.price = price
        self.time = time

class Grade(object):
    def __init__(self,name,course):
        self.name = name
        self.course = course
        self.student = []
        self.student_info = {}

    def grade_info(self):
        print('%s班 课程:%s'%(self.name,self.course))
        print('学生:')
        for i in self.student:
            print('%s 年龄:%s 性别:%s 成绩:%s'%(i,self.student_info[i].age,self.student_info[i].sex,self.student_info[i].score))

    def modify_score(self,name,score):
        self.student_info[name].score = score
school.py

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python3-关于GitHub的最基本操作

下一篇:Day_05 字典知识整理