Python-Level1-day14:属性封装思想与mvc功能完善,类型标注,多继承优缺点,模块导入方式

作业
1. 三合一
2. 当天练习独立完成
​
3. 创建商品管理系统
    -- 添加商品信息
​
4. 创建员工管理系统
    -- 添加员工信息
​
总结:
封装:分成几个类,每个类数据与行为
继承:父类与子类的隔离,统一,抽象
多态:子类对父类的重写
​

​
class CommodityModel:
​
    def __init__(self, name="", price=0):
        self.name = name
        self.price = price
        self.sid = 0
​
​
class CommodityView:
​
    def __init__(self, controller):
        self.controller = controller
​
    def display_menu(self):
        print("按1键录入商品信息")
        print("按2键显示商品信息")
        print("按3键删除商品信息")
        print("按4键修改商品信息")
​
    def select_menu(self):
        item = input("请输入您的选项:")
        if item == "1":
            self.input_commodity()
        elif item == "2":
            pass
​
    def input_commodity(self):
        cmd = CommodityModel()
        cmd.name = input("请输入商品姓名:")
        cmd.price = int(input("请输入商品单价:"))
        self.controller.add_comodity(cmd)
        print("添加成功")
​
​
class CommodityController:
    start_id = 1000
​
    @classmethod
    def set_comodity_id(cls, com):
        cls.start_id += 1
        com.sid = cls.start_id
​
    def __init__(self):
        self.comoditys = []
​
    def add_comodity(self, com):
        CommodityController.set_comodity_id(com)
        self.comoditys.append(com)
​
​
controller = CommodityController()
view = CommodityView(controller)
while True:
    view.display_menu()
    view.select_menu()
​
class EmployeeModel:
​
    def __init__(self, did=0, name="", money=0):
        self.eid = 0
        self.did = did
        self.name = name
        self.money = money
​
​
class EmployeeView:
​
    def __init__(self, controller):
        self.controller = controller
​
    def display_menu(self):
        print("按1键录入员工信息")
        print("按2键显示员工信息")
        print("按3键删除员工信息")
        print("按4键修改员工信息")
​
    def select_menu(self):
        item = input("请输入您的选项:")
        if item == "1":
            self.input_employee()
        elif item == "2":
            pass
​
    def input_employee(self):
        emp = EmployeeModel()
        emp.name = input("请输入员工姓名:")
        emp.did = int(input("请输入部门编号:"))
        emp.money = int(input("请输入员工薪资:"))
        self.controller.add_employee(emp)
        print("添加成功")
​
​
class EmployeeController:
    start_id = 1000
​
    @classmethod
    def set_employee_id(cls, emp):
        emp.eid = cls.start_id
        cls.start_id += 1
​
    def __init__(self):
        self.employees = []
​
    def add_employee(self, emp):
        EmployeeController.set_employee_id(emp)
        self.employees.append(emp)
​
​
controller = EmployeeController()
view = EmployeeView(controller)
while True:
    view.display_menu()
    view.select_menu()
​
"""
    学生管理系统:进一步变量与方法的属性上封装,让别人好调用,
    不暴露太多给别人,羞羞。不至于看到一大堆用不到函数
    添加功能:显示学生信息
             删除学生信息
             修改学生信息
​
"""
​
from typing import List
​
​
class StudentModel:
​
    def __init__(self, name="", age=0, score=0, sid: int = 0):
        self.name = name  # type:str
        self.age = age  # type:int
        self.score = score  # type:int
        self.sid = sid  # 学生全球唯一标识符
​
    def __str__(self):
        return f"name:{self.name},age:{self.age},score:{self.score},sid:{self.sid}"
​
    def __eq__(self, other):
        return self.sid == other
​
​
class StudentView:
    """
        学生视图:处理界面逻辑
    """
​
    def __init__(self, controller):
        self.__controller = controller  # type:StudentController
​
    def __display_menu(self):
        print("按1键录入学生信息")
        print("按2键显示学生信息")
        print("按3键删除学生信息")
        print("按4键修改学生信息")
​
    def __select_menu(self):
        item = input("请输入您的选项:")
        if item == "1":
            # 先写方法调用,再alt+回车自动生成
            self.__input_student()
        if item == "2":
            self.__display_students()
        if item == "3":
            self.__delate_students()
        if item == "4":
            self.__modity_student()
​
    def __input_student(self):
        stu = StudentModel()
        stu.name = input("请输入学生姓名:")
        stu.score = int(input("请输入学生成绩:"))
        stu.age = int(input("请输入学生年龄:"))
        self.__controller.add_student(stu)
        print("添加成功")
​
    def main(self):
        while True:
            self.__display_menu()
            self.__select_menu()
​
    def __display_students(self):
        for item in self.__controller.students:
            print(item)
​
    def __delate_students(self):
        sid = int(input("请输入要删除学生的sid"))
        if self.__controller.remove_student(sid):
            print("删除成功")
        else:
            print("删除失败")
​
    def __modity_student(self):
        stu = StudentModel()
        stu.sid = int(input("请输入要修改学生的sid"))
        stu.score = int(input("请输入要修改学生的分数"))
        stu.age = int(input("请输入要修改学生的年龄"))
        stu.name = input("请输入要修改学生的姓名")
        if self.__controller.update_student(stu):
            print("修改成功")
        else:
            print("修改失败")
​
​
class StudentController:
    """
        学生控制器:负责处理业务逻辑
    """
​
    __start_id = 1000  # 类变量
​
    @classmethod  # 类方法
    def __set_student_id(cls, stu):
        stu.sid = cls.__start_id
        cls.__start_id += 1
​
    def __init__(self):
        self.__students = []  # type:List[StudentModel]
​
    @property  # 就是为了单纯提醒一下调用者,这个变量我私有的,给你读写功能但要小心用
    def students(self):
        return self.__students
​
    def add_student(self, stu: StudentModel):  # 这个不用私有化,view要用
        StudentController.__set_student_id(stu)
        self.__students.append(stu)
​
    def remove_student(self, sid: int) -> bool:
        if sid in self.__students:
            self.__students.remove(sid)
            return True
        return False
​
    def update_student(self, stu: StudentModel) -> bool:
        for item in self.__students:
            if item.sid == stu.sid:
                item.name = stu.name
                item.score = stu.score
                item.age = stu.age
                return True
        return False
​
​
controller = StudentController()
view = StudentView(controller)
view.main()
​

 

 

"""
练习:
  商品管理系统:进一步变量与方法的属性上封装,
             让别人好调用,不至于看到一大堆用不到函数
​
   添加功能:  显示商品信息
             删除商品信息
             修改商品信息
"""
from typing import List
​
​
class CommodityModel:
​
    def __init__(self, name="", price=0):
        self.name = name  # type:str
        self.price = price  # type:int
        self.cid = 0  # type:int
​
    def __eq__(self, other):
        return self.cid == other
​
    def __str__(self):
        return f"name:{self.name},price:{self.price}"
​
​
class CommodityView:
​
    def __init__(self, controller):
        self.__controller = controller  # type: CommodityController
​
    def __display_menu(self):
        print("按1键录入商品信息")
        print("按2键显示商品信息")
        print("按3键删除商品信息")
        print("按4键修改商品信息")
​
    def __select_menu(self):
        item = input("请输入您的选项:")
        if item == "1":
            self.__input_commodity()
        elif item == "2":
            self.__display_comoditys()
        elif item == "3":
            self.__delate_comodity()
        elif item == "4":
            self.__modity_comodity()
​
    def __input_commodity(self):
        cmd = CommodityModel()
        cmd.name = input("请输入商品名称:")
        cmd.price = int(input("请输入商品单价:"))
        self.__controller.add_comodity(cmd)
        print("添加成功")
​
    def main(self):
        while True:
            self.__display_menu()
            self.__select_menu()
​
    def __display_comoditys(self):
        for item in self.__controller.comoditys:
            print(item)
​
    def __delate_comodity(self):
        cid = int(input("请输入商品cid"))
        if self.__controller.remove_comidity(cid):
            print("删除成功")
        else:
            print("删除失败")
​
    def __modity_comodity(self):
        com = CommodityModel()
        com.name = input("请输入要修改的商品name")
        com.cid = int(input("请输入要修改的商品cid"))
        com.price = int(input("请输入要修改的商品price"))
        if self.__controller.update_comodity(com):
            print("修改成功")
        else:
            print("修改失败")
​
​
class CommodityController:
    __start_id = 1000
​
    @classmethod
    def __set_comodity_id(cls, com):
        cls.__start_id += 1
        com.cid = cls.__start_id
​
    def __init__(self):
        self.__comoditys = []  # type:List[CommodityModel]
​
    @property
    def comoditys(self):
        return self.__comoditys
​
    def add_comodity(self, com: CommodityModel):
        CommodityController.__set_comodity_id(com)
        self.__comoditys.append(com)
​
    def remove_comidity(self, cid: int):
        if cid in self.__comoditys:
            self.__comoditys.remove(cid)
            return True
        return False
​
    def update_comodity(self, com: CommodityModel):
        for item in self.__comoditys:
            if item.cid == com.cid:
                item.__dict__ = com.__dict__
                return True
        return False
​
​
controller = CommodityController()
view = CommodityView(controller)
view.main()
​
"""
    类型标注 1.增强类型检测
            2.提示对应的方法操作
​
    python语言不用类型标注,导致不知道传入什么类型参数给函数
    优点是适合计算,不用什么什么类型变量
    缺点是传入类型时候就不知道是什么类型
"""
​
​
# 1 变量:类型   -----参数标注
def func(data: str):
    data.count()
​
​
func("dpq")  # 明确参数传递字符串类型
​
​
# 2 -> int -----返回值类型标注
def func01() -> int:
    return 10
​
​
# 3 对实例变量标注  #type:int
class Myclass:
    def __init__(self, data: int):
        self.data = data  # type:int
​
​
# 4 复合类型标注  记得还得加上import
from typing import List, Tuple, Dict
​
list01 = ["abc", "def"]  # type:List[str]
list02 = (1,)  # type:Tuple[int]
dict01 = {1: "2"}  # type:Dict[int,str]
list01[0].split()
​
# 5 标注多种类型,自己没有默认类型
# 得import union
from typing import Union
​
​
def func02(data: Union[int, str]):  # data可以是int或str
    data.split()
​
​
# 5 支持多种可选类型,自己有默认类型
# 得import Optional
from typing import Optional
​
​
def func03(data: Optional[int, str] = ""):  # data可以是int或str 自己默认参数类型str
    print(data)
​
"""
    多继承:单纯复用,没有多态
"""
​
​
class A:
    def func01(self):
        print("func01")
​
​
class B:
    def func02(self):
        print("func02")
​
​
# 分析这段代码
# 优点:最简单的代码复用方式
# 缺点:增加新父类型,必须修改C代码,违法开闭原则
class C(A, B):
    def func03(self):
        self.func01()
        self.func02()
​
​
c = C()
c.func03()
​
"""
    改进:多态复用
"""
​
​
class Father:
    def work(self):
        pass
​
​
class Mom:
    def play(self):
        pass
​
​
class dada1(Father):
    def work(self):
        print("work1")
​
​
class dada2(Father):
    def work(self):
        print("work2")
​
​
class mom1(Mom):
    def play(self):
        print("play1")
​
​
class mom2(Mom):
    def play(self):
        print("play2")
​
​
class kehuduan_son:
    def __init__(self, target1, target2):
        self.target1 = target1
        self.target2 = target2
​
    def life(self):
        self.target1.work()
        self.target2.play()
​
​
ma = mom1()
ba = dada2()
son = kehuduan_son(ba, ma)
son.life()
​

 

 

"""
    多继承:  1.作用是隔离多个维度变化
            2.同名方法解析顺序---几个类方法名称相同了处理方法
​
"""
class A:
    def func01(self):
        print("A----func01")
class B:
    def func01(self):
        print("B----func01")
​
​
class C(A,B):
    def func01(self):
        print("C----func01")
        #self.func01()通过super就不会认为调自己报错了
        super().func01()#默认调用A方法(左边优先)
        #B.func01#强制调用B方法
​
c =C()
c.func01()#两个父类方法名称相同,默认按照从左到右的方向,谁优先采取谁
#要想调用B类的func01 用B.func01()
"""
练习:写出下列代码在终端中执行效果
"""
​
​
class A:
    def func01(self):
        print("A")
        super().func01
​
​
class B:
    def func01(self):
        print("B")
​
​
class C(A, B):
    def func01(self):
        print("C")
        super().func01()
​
​
class D(A, B):
    def func01(self):
        print("D")
        super().func01()
​
​
class E(C, D):
    def func01(self):
        print("E")
        super().func01()
​
​
e = E()
e.func01()  # E -> C -> D -> A -> B
print(E.mro())
​
"""
    多继承
    加个爷爷类
"""
​
​
class A:
    def func01(self):
        print("A----func01")
​
​
class B(A):
    def func01(self):
        print("B----func01")
        super().func01()
​
​
class C(A):
    def func01(self):
        print("C----func01")
        super().func01()
​
​
class D(B, C):
    def func01(self):
        print("D----func01")
        super().func01()  # 先左后右
​
​
d = D()
d.func01()
#我们逻辑:D -B -A
# D -> B-->C ->A
print(D.mro())#通过mro查看调用级别
#[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
​
​
​
# 导入方式1  import 模块名称
# 用法 :模块(py文件)名称.成员名称
import module01  # 标蓝共同文件夹,就会有提示了,不标注不报错哦
​
module01.func01()
​
# 导入方式2 from 模块名称 import 成员名称
# 注意这个方法如果导入的成员与当前文件有重名的成员,
# 就会导致优先调用较近成员
from module01 import func01
from module01 import *  # 把这个模块所有成员都拿过来,就不用一个一个拿了
​
func01()  # 调用模块里面的func01
​
#exercise02_module模块,用于导入方式练习
data = 100
​
​
def func01():
    print("func01执行喽")
​
​
class MyClass:
    def func02(self):
        print("func02执行喽")
​
    @classmethod
    def func03(cls):
        print("func03执行喽")
​
# 方式1
from exercise02_module import *
​
​
print(data)
​
func01()
​
m1 = MyClass()
m1.func02()
MyClass.func03()
​
#方式2
import exercise02_module
​
print(exercise02_module.data)
​
exercise02_module.func01()
​
m1 = exercise02_module.MyClass()
m1.func02()
exercise02_module.MyClass.func03()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dpq666dpq666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值