首页技术为王Python面向对象程序设计

面向对象程序设计

分类Python时间2026-09-05 09:42:10发布信义之树浏览105
导读:一、Day1""" 类(组织代码的方式 类别 设计图 变量 + 函数组成的新的数据类型 对象 通过实例化类得到的 相当于根据设计图设计出来的具体的产品 """ # class关键...

一、Day1

"""
类(组织代码的方式)  类别  设计图
变量 + 函数组成的新的数据类型

对象
通过实例化类得到的  相当于根据设计图设计出来的具体的产品
"""


# class关键字定义类
class Movie:
    # 构造函数:初始化对象的属性和值
    # self约定俗成的名称,代表调用该方法的对象
    def __init__(self, name, type, year):
        self.name = name
        self.type = type
        self.year = year

    def say(self):
        print(f"电影{self.name}的类型是{self.type},上映年份是{self.year}")


# 调用类 类名(参数)  ==> 实例化 ==> 创建对象 ==> 自动调用__init__函数 ==> 传参
# 类名后面的参数,按照构造函数的形参传递
m1 = Movie("昆池岩", "爱情", 2020)
m2 = Movie("寂静岭", "儿童", 2018)
# 默认保存的是对象的数据地址
print(m1)

# 访问:对象.属性
print(m1.name, m1.type, m1.year)
# __dict__ 内置属性 用字典的形式显示对象
print(m1.__dict__)

# 对象.方法
m1.say()
m2.say()

print(Movie.__dict__)
print("weakref",Movie.__weakref__)
# 类外修改可以,不建议直接在类修改一个对象的属性值  ==> 封装
m1.name = "灰姑娘"
print(m1.__dict__)






"""
数瞰商智运营系统V1  ==> 纯逻辑
数瞰商智运营系统V2  ==> 使用函数

"""
# \033 转义序列开始 34蓝色 m结束序列
BLUE = "\033[34m"
YELLOW = "\033[33m"
GREEN = "\033[32m"
RED = "\033[31m"
# 重置颜色
RESET = "\033[0m"

list_prd = []


# 1.显示菜单
def display_menu():
    print(f"{BLUE}按1键添加商品信息")
    print("按2键显示商品信息")
    print("按3键修改商品信息")
    print("按4键删除商品信息")
    print("按5键退出系统")


# 2.选择菜单
def select_menu():
    choose_numer = input("请输入服务数字:")
    if choose_numer == "1":
        res = input_prd()
        print(f"{GREEN}添加成功~") if res else print(f"{RED}添加失败~")
    elif choose_numer == "2":
        res = display_prd()
        print(f"{RED}{res}") if res else ""
    elif choose_numer == "3":
        res = update_prd()
        print(f"{GREEN}修改成功~") if res == True else print(f"{RED}{res}")
    elif choose_numer == "4":
        res = delete_prd()
        print(f"{GREEN}删除成功~") if res == True else print(f"{RED}{res}")
    elif choose_numer == "5":
        print("Bye~")
        # 终止Python进程
        exit()
    else:
        print("不儿~你有病吧")


# 3.添加商品
def input_prd():
    # 空格替换
    id = input("请输入ID:").replace(" ", "")
    # id只能是整数
    if id.isdigit():
        id = int(id)
    else:
        print(f"{RED}ID必须是数字!{RESET}")
        return

    title = input("请输入标题:").repl1ace(" ", "")
    price = input("请输入价格:").replace(" ", "")

    if not id or not title or not price:
        print(f"{RED}内容不能为空{RESET}")
        return

    # 价格可以是小数,可以是整数(先不考虑负数)
    if price.replace(".", '', 1).isdigit():
        price = float(price)
    else:
        print(f"{RED}价格必须是数字!")
        return

    dict_prd = {
        "id": id,
        "title": title,
        "price": price
    }

    list_prd.append(dict_prd)
    return True


# 4.显示商品
def display_prd():
    if list_prd:
        for item in list_prd:
            print(f"{YELLOW}ID:{item['id']}的商品标题是{item['title']},价格为{item['price']}")
    else:
        return "暂无商品信息"


# 5.修改商品
def update_prd():
    id = int(input("请输入要修改商品的ID:").replace(" ", ""))
    for item in list_prd:
        if item['id'] == id:
            new_title = input(f"新标题(原:{item['title']}):").replace(" ", "")
            new_price = input(f"新价格(原:{item['price']}):").replace(" ", "")

            if not new_title or not new_price:
                return "内容不能为空!"

            if new_price.replace(".", '', 1).isdigit():
                new_price = float(new_price)
            else:
                return "价格必须是数字!"

            item["title"] = new_title
            item["price"] = new_price
            return True
    else:
        return "商品不存在"


# 6.删除商品
def delete_prd():
    if not list_prd:
        return "暂无商品信息"
    else:
        id = int(input("请输入要删除商品的ID:").replace(" ", ""))
        for item in list_prd:
            if item['id'] == id:
                list_prd.remove(item)
                return True
        else:
            return "商品不存在~"


# 运行函数
def main():
    while True:
        display_menu()
        select_menu()


main()

        执行结果:

<__main__.Movie object at 0x0000020204F94440>
昆池岩 爱情 2020
{'name': '昆池岩', 'type': '爱情', 'year': 2020}
电影昆池岩的类型是爱情,上映年份是2020
电影寂静岭的类型是儿童,上映年份是2018
{'__module__': '__main__', '__firstlineno__': 11, '__init__': <function Movie.__init__ at 0x0000020204F2F8A0>, 'say': <function Movie.say at 0x0000020204F2F950>, '__static_attributes__': ('name', 'type', 'year'), '__dict__': <attribute '__dict__' of 'Movie' objects>, '__weakref__': <attribute '__weakref__' of 'Movie' objects>, '__doc__': None}
weakref <attribute '__weakref__' of 'Movie' objects>
{'name': '灰姑娘', 'type': '爱情', 'year': 2020}
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统
请输入服务数字:4
暂无商品信息
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统
请输入服务数字:3
请输入要修改商品的ID:11
商品不存在
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统
请输入服务数字:5
Bye~

二、Day2

"""
MVC 组织代码的一种方式
分层 每层各司其职

M层 模型层  Model 负责数据模型(对象有哪些属性)
V层 视图层  View  负责显示数据和界面
C层 控制器  Controller 负责业务逻辑

"""


# 输入框 V层
# 对象的属性 M层
# 如何添加电影 C层

# M层


class Goods:
    def __init__(self, id, title, price):
        self.id = id
        self.title = title
        self.price = price

    def say(self):
        print(f"{YELLOW}ID:{self.id}的商品标题是{self.title},价格为{self.price}")


list_prd = []
good_obj = Goods(1, "手机", 1000) 
list_prd.append(good_obj)

print(list_prd)
print([g.__dict__ for g in list_prd])
print(list_prd[0].title)




class MovieModel:
    def __init__(self, name, year):
        self.name = name
        self.year = year


# V层
class MovieView:
    def __init__(self):
        self.controller = MovieController()

    # 列表不直接放在V的原因,C用起来费劲: C层控制业务,所以放C中,C用起来方便
    def input_movie(self):
        name = input("输入电影名称:")
        year = input("输入电影年份:")

        # 没有规定说必须V调M,这是因为方便
        movie_obj = MovieModel(name, year)
        # print(movie_obj.name, movie_obj.year)
        self.controller.add_movie(movie_obj)
        # print([(item.name,item.year) for item in self.controller.list_movie])
      


# C层
class MovieController:
    def __init__(self):
        self.list_movie = []

    def add_movie(self, movie_obj):
        self.list_movie.append(movie_obj)
        # print(item for item in self.list_movie)
        print([(item.name,item.year) for item in self.list_movie])


view = MovieView()
while True:
    view.input_movie()
    # print(item.name for item in view.controller.list_movie)

        执行结果:

[<__main__.Goods object at 0x00000144EA6146E0>]
[{'id': 1, 'title': '手机', 'price': 1000}]
手机
输入电影名称:功夫女足 
输入电影年份:2026
[('功夫女足 ', '2026')]
输入电影名称:功夫足球
输入电影年份:2001
[('功夫女足 ', '2026'), ('功夫足球', '2001')]
输入电影名称:

三、Day3

"""
面向对象的三大特征
封装
   通过私有属性或者私有方法对外隐藏类内部的实现细节
   外部只能通过指定的方法(公开)来操作对象,无法直接修改和访问
   通过双下划线实现 __属性  __方法
继承
多态
"""


class Movie:
    def __init__(self, name, type, year):
        # 公开的
        # 类的内部或外部或子类都能直接使用
        self.name = name
        # 受保护的 约定
        # 类的内部或子类都能直接使用,外部无法直接使用
        self._type = type
        # 私有的 名称修饰机制 改写名字  _类名__属性名
        # 类的内部能直接使用, 子类或外部无法直接使用
        self.__year = year

    def __say(self):
        print(f"电影{self.name}上映时间{self.__year}类型是{self._type}")

    def get_year(self):
        return self.__year

    def set_year(self, values):
        self.__year = values

    def hi(self):
        # 调用私有方法say
        self.__say()


m1 = Movie("昆池岩", "爱情", 2020)
print(m1.name)
print(m1._type)
# print(m1.__year)#报错 AttributeError: 'Movie' object has no attribute '__year'
# 通过公开的方法操作
print(m1.get_year())
m1.set_year(2028)
print(m1.get_year())
m1.hi()

# 强制访问私有属性
print(m1._Movie__year)
# 强制访问私有方法
m1._Movie__say()



"""
面向对象的三大特征
封装
   通过私有属性或者私有方法对外隐藏类内部的实现细节
   外部只能通过指定的方法(公开)来操作对象,无法直接修改和访问
   通过双下划线实现 __属性  __方法
继承
多态
"""


class Movie:
    def __init__(self, name, type, year):
        self.name = name
        self._type = type
        self.__year = year

    # 内置装饰器 允许一个类的方法,当做一个属性来访问
    @property
    def year(self):
        return self.__year

    @year.setter
    def year(self, values):
        self.__year = values


m1 = Movie("昆池岩", "爱情", 2020)
print(m1.year)
m1.year = 2029
m1.haha = 2028
print(m1.year)

print(m1.__dict__)




"""
面向对象的三大特征
封装
   通过私有属性或者私有方法对外隐藏类内部的实现细节
   外部只能通过指定的方法(公开)来操作对象,无法直接修改和访问
   通过双下划线实现 __属性  __方法
继承
   子承父业
   一个类可以拥有另外一个类的属性和方法
   父类 被继承的类
   子类 继承父类的类

多态
"""


# 电影类
class Movie:
    def play(self):
        print("播放")


# 动作电影
class ActionMovie(Movie):
    def show_action(self):
        print("动作电影")


# 搞笑电影
class ComedyMovie(Movie):
    def show_comedy(self):
        print("搞笑电影")


action = ActionMovie()
action.play()
action.show_action()

comedy = ComedyMovie()
comedy.play()
comedy.show_comedy()



"""
面向对象的三大特征
封装
   通过私有属性或者私有方法对外隐藏类内部的实现细节
   外部只能通过指定的方法(公开)来操作对象,无法直接修改和访问
   通过双下划线实现 __属性  __方法
继承
   子承父业
   一个类可以拥有另外一个类的属性和方法
   父类 被继承的类
   子类 继承父类的类

多态
"""


# 电影类
class Movie:
    def play(self):
        print("播放")


# 电影类型 网剧
class Film(Movie):
    def show_type(self, type):
        print(f"类型:{type}")


# 动作电影
class ActionMovie(Film):
    def show_action(self):
        print("动作电影")


# 搞笑电影
class ComedyMovie(Film):
    def show_comedy(self):
        print("搞笑电影")


action = ActionMovie()
action.play()
action.show_type("网剧")
action.show_action()

comedy = ComedyMovie()
comedy.play()
comedy.show_type("大片")
comedy.show_comedy()


# 电影类
class Movie:
    def __init__(self, name):
        self.name = name
    def play(self):
        print("播放")
# 动作电影
class ActionMovie(Movie):
    # 1.子类没有构造函数的时候,用父类的构造函数
    # 2.子类有自己的构造函数,用自己的
    # 3.既要父类的构造函数,又要子类自己的构造函数
    def __init__(self, name, year):
        # super()调用父类的构造函数
        super().__init__(name)
        self.year = year

    def show_action(self):
        print(f"动作电影{self.name}上映时间{self.year}")


action = ActionMovie("昆池岩", 2025)
action.play()
action.show_action()


# 电影类
class Movie:
    def __init__(self, name):
        self.name = name

    def play(self):
        print("播放")


# 动作电影
class ActionMovie(Movie):
    def __init__(self, year):
        self.year = year

    # 重写了自定义函数
    def play(self):
        print(f"动作电影上映时间{self.year}")

    # 重写内置函数
    def __str__(self):
        return f"嘻嘻嘻嘻嘻嘻嘻"


action = ActionMovie(2025)
action.play()
print(action)  # 默认行为是打印对象数据地址



# 电影类
class Movie:
    def __init__(self, name):
        self.name = name

    # 重写
    def __eq__(self, other):
        print(id(self))
        print(id(other))
        return self.name == other.name


m1 = Movie("雷神")
print("m1对象地址", id(m1))
m2 = Movie("雷神")
print("m2对象地址", id(m2))
m3 = Movie("蚁人")

# 默认比较的是数据地址,通过 __eq__重写规则
print(m1 == m2)
print(m1 == m3)

list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(id(list1))
print(id(list2))
# 值
print(list1 == list2)  # T

        执行结果:

池岩
爱情
2020
2028
电影昆池岩上映时间2028类型是爱情
2028
电影昆池岩上映时间2028类型是爱情
2020
2029
{'name': '昆池岩', '_type': '爱情', '_Movie__year': 2029, 'haha': 2028}
播放
动作电影
播放
搞笑电影
播放
类型:网剧
动作电影
播放
类型:大片
搞笑电影
播放
动作电影昆池岩上映时间2025
动作电影上映时间2025
嘻嘻嘻嘻嘻嘻嘻
m1对象地址 1969124099808
m2对象地址 1969124001744
1969124099808
1969124001744
True
1969124099808
1969124002064
False
1969124238400
1969124238464
True

四、Day4

"""
一些比较有意思的运算符和函数
"""
a1 = 1
b1 = 1

a2 = [1, 2, 3]
b2 = [1, 2, 3]

a3 = (1, 2, 3)
b3 = (1, 2, 3)


class Movie:
    def __init__(self, title):
        self.title = title


m1 = Movie("749")
m2 = Movie("749")

# 比较运算符  比较值
print("1:",a1 == b1)
print("2:",a2 == b2)
print("3:",a3 == b3)
print("4:",m1 == m2)  # 内存地址

# 身份运算符
# is  判断2个对象是否为同一个对象(内存地址是不是一样的)
# is not 判断2个对象不是同一个对象
print(a1 is b1)  # T
print(a2 is b2)  # F
print(a3 is b3)  # T
print(m1 is m2)  # F


# 动态生成的元组
c3 = (1, 2, 3)
d3 = tuple([1, 2, 3])  # 通过转换得到的元组

print("动态生成:",c3 is d3)  # 你可能会惊讶地发现,这里输出的是 False!


class Person:
    pass


class Director(Person):
    pass


class Movie:
    pass


p1 = Person()
d1 = Director()
m1 = Movie()

# isinstance函数
# 检查一个对象,是不是指定类型的实例,或者指定类型的子类的实例
# 人对象 是不是 人类的实例
print(isinstance(p1, Person))  # T
# 导演对象 是不是 人类的实例
print(isinstance(d1, Person))  # T
# 人对象 是不是 导演类的实例
print(isinstance(p1, Director))  # F

# issubclass函数
# 检查一个类,是不是另外一个类的子类,或者是不是同一个类
print(issubclass(Person, Movie))  # F
print(issubclass(Movie, Person))  # F
print("在这:",issubclass(Director, Person))  # T

# 应用场景 动态类型验证
def f1(data: list):
    if isinstance(data, list):
        print(data)
    else:
        # 抛出异常
        raise TypeError("类型错误")

f1([1,2,3,4])
# f1(1)


"""
类的成员
实例成员:属于类的实例(对象)
    实例属性,实例方法
类成员:属于类本身的,不属于类的任何实例(对象)
    类属性 静态方法 类方法(不提,太复杂了!!!)
"""


class Movie:
    # 类属性 所有实例共享,描述了对象共有的数据 类名.属性
    HD = "蓝光"
    __accord = "DP"  # 私有的类属性

    def __init__(self, name):
        # 实例属性 在构造函数中定义的属性 对象.属性
        self.name = name

    # 实例方法 在类中定义,至少有一个self形参,用来绑定对象 对象.方法名()
    def say(self):
        print(f"电影名:{self.name}{Movie.HD}")

    # 静态方法 类名.方法名()
    @staticmethod
    def from_city():
        print(f"来自大城市铁岭")


print("*"*20)

m1 = Movie(749)
m2 = Movie(759)
print(m1.__dict__)  #以字典的形式,展示该实例对象当前拥有的所有“实例属性”及其对应的值。
print(m2.__dict__)
m1.say()
print(Movie.__dict__)
print(Movie.HD, Movie._Movie__accord)
Movie.from_city()



"""

"""


class Director2:
    def __init__(self, director):
        self.director = director


class Actor:
    def __init__(self, actor):
        self.actor = actor


# 多继承  
class Movie2(Director2, Actor):
    def __init__(self, director, actor, name):
        Director2.__init__(self, director)
        Actor.__init__(self, actor)
        self.name = name

    def get_details(self):
        print(f"电影{self.name}的导演是{self.director},演员{self.actor}")


print("*"*20)

movie2 = Movie2("布莱恩", "汤姆", "碟中谍")
print(movie2.__dict__)
movie2.get_details()


"""
集合 没有键只有值的字典
由一系列不重复且不可变的值组成的可变散列容器
"""
set1 = {1, 2, 3, 2, 3}
set2 = {"C++", "P++", "J++", (1, 2, 3)}
print("*"*20)
# 添加
set2.add("g++")
set2.update(["语文", "英语"])

# 删除
set2.remove("J++")

# 遍历
for item in set2:
    print(item)
print(set1, set2)

# 推导式
print({item for item in [1, 2, 3, 2, 1, 3]})
print([item for item in [1, 2, 3, 2, 1, 3]])




print("*"*20)

list1 = [1, 2, 3]
tuple1 = (1, 2, 3)
dict1 = {'a': 1, 'b': 2}
set1 = {1, 2, 3}

print(list(set1))
print(list(dict1.items()))
print(tuple(set1))
print(set(list1))

print(dict([('a', 1), [1, 2]]))



"""
创建一个员工类 姓名 岗位

比较2个员工岗位是否一致,是返回true
比较2个员工所有信息否一致,是返回true
"""


class Emp:
    def __init__(self, name, job):
        self.name = name
        self.job = job

    def __eq__(self, other):
        # return self.job == other.job
        return self.job == other.job and self.name == other.name
        return self.__dict__ == other.__dict__


e1 = Emp("xiaoyi", "UI")
e2 = Emp("xiaoyu", "UI")
e3 = Emp("xiaoyi", "UI")

print("*"*20)
print(e1 == e2)
print(e1 == e3)



"""
创建文章类,使用类属性作为文章的id,实现自增
构造函数接收文章的标题和内容
实例方法打印文章信息
静态方法打印最后一篇的文章id
"""

class Article:
    id = 0  #类属性是所有实例共享的

    def __init__(self, title, content):
        Article.id += 1
        self.id = Article.id
        self.title = title
        self.content = content

    def say(self):
        print(f"ID:{self.id}标题:{self.title},内容:{self.content}")

    @staticmethod
    def get_lastid():
        print(f"{Article.id}")


a1 = Article("震惊", "某老师午休的时候竟然睡觉!")
a2 = Article("围城", "城里的人想出去,城外的人想进来")

a1.say()
Article.get_lastid()

        执行结果:

1: True
2: True
3: True
4: False
True
False
True
False
动态生成: False
True
True
False
False
False
在这: True
[1, 2, 3, 4]
********************
{'name': 749}
{'name': 759}
电影名:749蓝光
{'__module__': '__main__', '__firstlineno__': 96, 'HD': '蓝光', '_Movie__accord': 'DP', '__init__': <function Movie.__init__ at 0x0000013E43F937F0>, 'say': <function Movie.say at 0x0000013E43F938A0>, 'from_city': <staticmethod(<function Movie.from_city at 0x0000013E43F93950>)>, '__static_attributes__': ('name',), '__dict__': <attribute '__dict__' of 'Movie' objects>, '__weakref__': <attribute '__weakref__' of 'Movie' objects>, '__doc__': None}
蓝光 DP
来自大城市铁岭
********************
{'director': '布莱恩', 'actor': '汤姆', 'name': '碟中谍'}
电影碟中谍的导演是布莱恩,演员汤姆
********************
P++
英语
(1, 2, 3)
C++
g++
语文
{1, 2, 3} {'P++', '英语', (1, 2, 3), 'C++', 'g++', '语文'}
{1, 2, 3}
[1, 2, 3, 2, 1, 3]
********************
[1, 2, 3]
[('a', 1), ('b', 2)]
(1, 2, 3)
{1, 2, 3}
{'a': 1, 1: 2}
********************
False
True
ID:1标题:震惊,内容:某老师午休的时候竟然睡觉!
2

五、shukanV3

"""
数瞰商智运营系统V1  ==> 纯逻辑
数瞰商智运营系统V2  ==> 使用函数
数瞰商智运营系统V3  ==> 使用类和对象形式来代替字典

"""
# \033 转义序列开始 34蓝色 m结束序列
BLUE = "\033[34m"
YELLOW = "\033[33m"
GREEN = "\033[32m"
RED = "\033[31m"
# 重置颜色
RESET = "\033[0m"


class Goods:
    def __init__(self, id, title, price):
        self.id = id
        self.title = title
        self.price = price

    def say(self):
        print(f"{YELLOW}ID:{self.id}的商品标题是{self.title},价格为{self.price}")


list_prd = []


# 1.显示菜单
def display_menu():
    print(f"{BLUE}按1键添加商品信息")
    print("按2键显示商品信息")
    print("按3键修改商品信息")
    print("按4键删除商品信息")
    print("按5键退出系统")


# 2.选择菜单
def select_menu():
    choose_numer = input("请输入服务数字:")
    if choose_numer == "1":
        res = input_prd()
        print(f"{GREEN}添加成功~") if res else print(f"{RED}添加失败~")
    elif choose_numer == "2":
        res = display_prd()
        print(f"{RED}{res}") if res else ""
    elif choose_numer == "3":
        res = update_prd()
        print(f"{GREEN}修改成功~") if res == True else print(f"{RED}{res}")
    elif choose_numer == "4":
        res = delete_prd()
        print(f"{GREEN}删除成功~") if res == True else print(f"{RED}{res}")
    elif choose_numer == "5":
        print("Bye~")
        # 终止Python进程
        exit()
    else:
        print("不儿~你有病吧")


# 3.添加商品
def input_prd():
    # 空格替换
    id = input("请输入ID:").replace(" ", "")
    # id只能是整数
    if id.isdigit():
        id = int(id)
    else:
        print(f"{RED}ID必须是数字!{RESET}")
        return

    title = input("请输入标题:").replace(" ", "")
    price = input("请输入价格:").replace(" ", "")

    if not id or not title or not price:
        print(f"{RED}内容不能为空{RESET}")
        return

    # 价格可以是小数,可以是整数(先不考虑负数)
    if price.replace(".", '', 1).isdigit():
        price = float(price)
    else:
        print(f"{RED}价格必须是数字!")
        return

# """
# 和字典的区别只在这里:
#     dict_prd = {
#         "id": id,
#         "title": title,
#         "price": price
#     }
    #  list_prd.append(dict_prd)
# """



    # 对象
    good_obj = Goods(id, title, price)
    list_prd.append(good_obj)
    return True





# 4.显示商品
def display_prd():
    if list_prd:
        for item in list_prd:
            item.say()
    else:
        return "暂无商品信息"


# 5.修改商品
def update_prd():
    id = int(input("请输入要修改商品的ID:").replace(" ", ""))
    for item in list_prd:
        if item.id == id:
            new_title = input(f"新标题(原:{item.title}):").replace(" ", "")
            new_price = input(f"新价格(原:{item.price}):").replace(" ", "")

            if not new_title or not new_price:
                return "内容不能为空!"

            if new_price.replace(".", '', 1).isdigit():
                new_price = float(new_price)
            else:
                return "价格必须是数字!"

            item.title = new_title
            item.price = new_price
            return True
    else:
        return "商品不存在"


# 6.删除商品
def delete_prd():
    if not list_prd:
        return "暂无商品信息"
    else:
        id = int(input("请输入要删除商品的ID:").replace(" ", ""))
        for item in list_prd:
            if item.id == id:
                list_prd.remove(item)
                return True
        else:
            return "商品不存在~"


# 运行函数
def main():
    while True:
        display_menu()
        select_menu()


main()


六、shukanV4

"""
数瞰商智运营系统V1  ==> 纯逻辑
数瞰商智运营系统V2  ==> 使用函数
数瞰商智运营系统V3  ==> 使用类和对象形式来代替字典
数瞰商智运营系统V4  ==> 使用MVC重构代码

"""


# M层
class GoodsModel:
    def __init__(self, id, title, price):
        self.id = id
        self.title = title
        self.price = price


# V层
class GoodsView:
    def __init__(self):
        self.controller = GoodsController()

    def run(self):
        while True:
            self.display_menu()
            self.select_menu()

    # 显示菜单
    def display_menu(self):
        print("按1键添加商品信息")
        print("按2键显示商品信息")
        print("按3键修改商品信息")
        print("按4键删除商品信息")
        print("按5键退出系统")

    # 选择菜单
    def select_menu(self):
        choose_number = input(f"请输入服务数字:")
        if choose_number == "1":
            self.input_goods()
        elif choose_number == "2":
            self.display_goods()
        elif choose_number == "3":
            self.update_goods()
        elif choose_number == "4":
            self.delete_goods()
        elif choose_number == "5":
            print("Bye~")
            exit()
        else:
            print("不是儿你有病吧~")

    # 添加商品
    def input_goods(self):
        id = input("请输入商品的ID:").replace(" ", "")
        title = input("请输入商品的标题:").replace(" ", "")
        price = input("请输入商品的价格:").replace(" ", "")

        if not id or not title or not price:
            print("内容不能为空~")
            return

        if price.replace(".", "", 1).isdigit():
            price = float(price)
        else:
            print("价格必须是数字~")
            return

        # 创建商品对象
        good_obj = GoodsModel(id, title, price)
        if self.controller.add_goods(good_obj):
            print("添加成功")
        else:
            print("添加失败")

    # 显示商品
    def display_goods(self):
        if not self.controller.list_goods:
            print("暂无商品信息")
            return
        for item in self.controller.list_goods:
            print(f"ID:{item.id}商品标题:{item.title},价格{item.price}")

    def update_goods(self):
        id = input("请输入要修改的商品ID:").replace(" ", "")

        if not id:
            print("ID不能为空")
            return

        goods = self.controller.get_goods(id)

        if goods:
            title = input(f"新标题(原:{goods.title}):").replace(" ", "")
            price = input(f"新价格(原:{goods.price}):").replace(" ", "")

            if not title or not price:
                print("内容不能为空")
                return

            if price.replace(".", "", 1).isdigit():
                price = float(price)
            else:
                print("价格必须是数字~")
                return

            if self.controller.modify_goods(goods, title, price):
                print("修改成功")
            else:
                print("修改失败")

        else:
            print("暂无商品信息")

    def delete_goods(self):
        id = input("请输入要删除的商品ID:").replace(" ", "")

        if not id:
            print("ID不能为空")
            return

        # 根据id找商品,找到返回商品对象,找不到就是None
        goods = self.controller.get_goods(id)
        if goods:
            if self.controller.remove_goods(goods):
                print("删除成功")
            else:
                print("删除失败")
        else:
            print("查无此商品")

# C层  感觉这么多余呢,化简为繁了
class GoodsController:
    def __init__(self):
        self.list_goods = []

    def get_goods(self, id):
        for item in self.list_goods:
            if item.id == id:
                return item

    def add_goods(self, good_obj):
        self.list_goods.append(good_obj)
        print(self.list_goods)
        return True

    def modify_goods(self, goods, title, price):
        goods.title = title
        goods.price = price
        return True

    def remove_goods(self, goods):
        self.list_goods.remove(goods)
        return True


def main():
    view = GoodsView()
    view.run()


main()


































Python基础课程

游客 回复需填写必要信息
↑