day15

"""
    复习
    程序的结构
        文件夹(根目录)
            包package
                模块.py
                    类
                        函数
                            语句

    模块和包的作用:程序结构清晰
    导入:
        import 从根目录开始的路径.模块 as 别名
        别名.成员

        from 从根目录开始的路径.模块 import 成员
        直接使用成员

        from 从根目录开始的路径.模块 import *
        直接使用成员

    导包成功的标准:
        sys.path + 导包时的路径
        可以正确找到文件

    模块相关概念
        __name__

"""

if __name__ == "__main__":
    # 如果当前模块是主模块,才执行.
    print("测试代码")



# demo01
"""
    时间模块 time
    10:10
    练习:exercise01 / 02
"""
import time

# 1. 获取当前时间戳(从1970年1月1日到现在经过的秒数)
# 1568856576.399807
print(time.time())

# 2. 获取当前时间元组
# tm_year=2019, tm_mon=9, tm_mday=19, tm_hour=9, tm_min=33, tm_sec=31, tm_wday=3, tm_yday=262, tm_isdst=0
print(time.localtime())

# 3. 时间戳 --> 时间元组
time_tuple = time.localtime(1568856576.399807)
print(time_tuple)
print("年份:",time_tuple[0])
print("星期",time_tuple[6] + 1)

# 4. 时间元组 --> 时间戳
print(time.mktime(time_tuple))

# 5. 时间元组 --> str
print(time.strftime("%y/%m/%d %H:%M:%S",time_tuple))
print(time.strftime("%Y/%m/%d %H:%M:%S",time_tuple))

# 6. str --> 时间元组
print(time.strptime("19/09/19 09:29:36","%y/%m/%d %H:%M:%S"))



# demo02
"""
    异常处理
    练习:exercise03
    练习:信息管理系统
    练习:购物车 shopping__oo.py
"""


def div_apple(apple_count):
    """
        分苹果
    """
    person_count = int(input("请输入人数:"))  # ValueError
    result = apple_count / person_count  # ZeroDivisionError
    print("每人%d个苹果" % result)

# 处理目的:让异常(错误)流程 转换为 正常流程

""" 1. 统一处理所有异常
try:
    # 可能出错的代码
    div_apple(10)
# except Exception:# 可以拦截所有错误(异常)
except:
    print("程序出错啦")

print("后续逻辑")
"""

""" 2. 分门别类的处理各种异常(官方更建议)
try:
    # 可能出错的代码
    div_apple(10)
except ValueError:
    print("输入的不是整数,所以错误啦.")
except ZeroDivisionError:
    print("输入的是零,所以错误啦.")

print("后续逻辑")
"""

""" 可以处理错误执行逻辑,也可以处理没出错的执行逻辑
try:
    # 可能出错的代码
    div_apple(10)
except ValueError:
    print("输入的不是整数,所以错误啦.")
except ZeroDivisionError:
    print("输入的是零,所以错误啦.")
else:
    print("没出错执行的逻辑")

print("后续逻辑")
"""

try:
    # 可能出错的代码
    div_apple(10)
finally:
    # 如果出错了,虽然我解决不了,但有个事我必须做.
    print("管你错不错呢,一定做!")

print("后续逻辑")


# demo03
"""
    自定义异常类
    练习:exercise04.py
"""


class WeightError(Exception):
    def __init__(self, message="", code="", id=0):
        # super().__init__()
        self.message = message
        self.code = code
        self.id = id


class Wife:
    def __init__(self, name="", weight=0):
        self.name = name
        self.weight = weight

    @property
    def weight(self):
        return self.__weight

    @weight.setter
    def weight(self, value):
        if 20 <= value <= 200:
            self.__weight = value
        else:
            # 有意抛出异常
            # 传递的错误信息:错误原因,错误代码,错误编号,.....
            # raise Exception("体重超过范围")
            raise WeightError("体重超过范围", "if 20 <= value <= 200", 1001)


try:
    w01 = Wife("芳芳", 450)
except WeightError as e:
    print("错误编号是:", e.id)
    print("错误信息:", e.message)
    print("错误代码:", e.code)




# demo04
"""
    使用可迭代对象
"""

list01 = [234, 45, 54, 65, 6, 7, 8]

# 可以被for的条件:
#    对象具有__iter__方法

# for itme in list01:
#     print(itme)

# for原理:
# 1.  获取迭代器对象
iterator = list01.__iter__()
# 2. 获取下一个元素(迭代一次)
while True:
    try:
        item = iterator.__next__()
        print(item)
    # 3. 拦截StopIteration异常
    except StopIteration:
        break

# exercise01

"""
    练习1:定义函数,根据年月日计算星期数.
           星期一
           星期二
           ....
           星期日
"""
import time


def get_week(year, month, day):
    time_tuple = time.strptime("%d/%d/%d" % (year, month, day), "%Y/%m/%d")
    # print(time_tuple[6])# 3 --> 星期四
    # if time_tuple[6] == 0:
    #     return "星期一"
    # if time_tuple[6] == 1:
    #     return "星期二"
    tuple_weeks = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")
    return tuple_weeks[time_tuple[6]]

print(get_week(2019, 9, 19))


# exercise02
# 练习:定义函数,根据生日(年月日),计算活了多天.
#  公式:现在 - 生日
import time
# 11:25

def life_days(year, month, day):
    # year,month,day --> 时间元组
    time_tuple = time.strptime("%d/%d/%d" % (year, month, day), "%Y/%m/%d")
    life_second = time.time() - time.mktime(time_tuple)
    return life_second / 60 / 60 // 24


print("%d" % life_days(1999, 1, 1))

# exercise03
"""
    练习:定义函数,在控制台中获取年龄.
        要求:如果异常,或者年龄超过范围(0 -- 150)则重复获取
             直到正确为止.
"""


def get_age():
    while True:  # 重复
        try:
            age = int(input("请输入年龄:"))# 如果异常执行17行代码
            if 0 <= age <= 150:
                return age
            else:
                print("年龄超过范围")
        except:  # 异常状态 --> 正常状态
            print("输入有误")

print(get_age())

# 练习:对信息管理系统进行异常处理,要求:按照程序既定流程执行。
# exercise04
# 练习: 定义敌人类(姓名,攻击力),要求限制攻击力范围在0--50之间
#       如果不在范围内,抛出异常,
#       传递3个错误信息(错误编号/错误信息/错误代码)
class AtkError(Exception):
    def __init__(self, id=0, message="", code=""):
        super().__init__(message)
        self.error_id = id
        self.error_message = message
        self.error_code = code


class Enemy:
    def __init__(self, name="", atk=0):
        self.name = name
        self.atk = atk

    @property
    def atk(self):
        return self.__atk

    @atk.setter
    def atk(self, value):
        if 0 <= value <= 50:
            self.__atk = value
        else:
            raise AtkError(101, "攻击力不在范围内", "if 0<=value<=50")
            # 如果想偷偷懒,也可以尝试使用Exception传递多个错误信息.
            # raise Exception("a","b","c")


# try:
#     e01 = Enemy("灭霸", 100)
# except AtkError as e:
#     print(e.error_message)

try:
    e01 = Enemy("灭霸", 100)
except Exception as e:
    print(e.args[0])
    print(e.args[1])
    print(e.args[2])
# 17:05

# exercise05


# 练习1:使用for循环原理(迭代思想),获取元组中所有元素.
tuple01 = (4,4,5,6,7,9)
iterator = tuple01.__iter__()
while True:
    try:
        item = iterator.__next__()
        print(item)
    except StopIteration:
        break


# exercise06

# 练习2:不适用for循环,获取字典中所有记录.
dict01 = {"a": 1, "b": 2, "c": 3}
iterator = dict01.__iter__()
while True:
    try:
        key = iterator.__next__()
        print(key, dict01[key])
    except StopIteration:
        break

"""
    对购物车进行异常处理
"""


class CommodityModel:
    """
        商品模型
    """

    def __init__(self, id=0, name="", price=0):
        self.id = id
        self.name = name
        self.price = price


class OrderModel:
    """
        订单模型
    """

    def __init__(self, commodity=None, count=0, id=0):
        self.id = id
        self.commodity = commodity
        self.count = count

#shopping__oo

class ShoppingCartController:
    """
        购物车逻辑控制器
    """
    init_order_id = 0

    def __init__(self):
        self.__list_order = []
        self.__list_commodity_info = self.__load_commodity()

    @property
    def list_order(self):
        return self.__list_order

    @property
    def list_commodity_info(self):
        return self.__list_commodity_info

    def __load_commodity(self):
        """
            加载商品信息
        :return: 商品列表
        """
        return [
            CommodityModel(101, "屠龙刀", 10000),
            CommodityModel(102, "倚天剑", 10000),
            CommodityModel(103, "九阴白骨爪", 8000),
            CommodityModel(104, "九阳神功", 9000),
            CommodityModel(105, "降龙十八掌", 8000),
        ]

    def add_order(self, order_base_info):
        """
            添加订单
        :param order:订单基础信息
        """
        order_base_info.id = self.__generate_order_id()
        self.__list_order.append(order_base_info)

    def __generate_order_id(self):
        """
            生成订单编号
        :return: 订单编号
        """
        ShoppingCartController.init_order_id += 1
        return ShoppingCartController.init_order_id

    def get_total_price(self):
        """
            根据订单计算总价格
        :return:总价格
        """
        total_price = 0
        for item in self.__list_order:
            total_price += item.commodity.price * item.count
        return total_price

    def get_commodity_by_id(self, id):
        """
            获取指定的商品
        :param id: 商品编号
        :return: 商品对象
        """
        for item in self.__list_commodity_info:
            if item.id == id:
                return item


class ShoppingConsoleView:
    """
        购物车控制台界面视图
    """

    def __init__(self):
        self.__controller = ShoppingCartController()

    def __select_menu(self):
        """
            菜单选择 
        """
        while True:
            item = input("1键购买,2键结算。")
            if item == "1":
                self.__buying()
            elif item == "2":
                self.__settlement()

    def __buying(self):
        """
            购买
        """
        self.__print_commodity()
        self.__create_order()
        print("添加到购物车。")

    def __print_commodity(self):
        """
            打印商品信息
        """
        for commodity in self.__controller.list_commodity_info:
            print("编号:%d,名称:%s,单价:%d。" % (commodity.id, commodity.name, commodity.price))

    def __create_order(self):
        """
            创建订单
        """
        while True:
            # cid = int(input("请输入商品编号:"))
            cid = self.__input_number("请输入商品编号:")
            # 如果该商品存在,则退出循环,否则重新输入。
            commodity = self.__controller.get_commodity_by_id(cid)
            if commodity:
                break
            else:
                print("该商品不存在")
        # count = int(input("请输入购买数量:"))
        count = self.__input_number("请输入购买数量:")
        order = OrderModel(commodity, count)
        self.__controller.add_order(order)

    def __settlement(self):
        """
            结算
        """
        self.__print_order()
        total_price = self.__controller.get_total_price()
        self.__pay(total_price)

    def __print_order(self):
        """
            打印订单
        """
        for order in self.__controller.list_order:
            commodity = order.commodity
            print("商品:%s,单价:%d,数量:%d." % (commodity.name, commodity.price, order.count))

    def __pay(self, total_price):
        """
            支付
        :param total_price: 需要支付的价格
        :return:
        """
        while True:
            # money = float(input("总价%d元,请输入金额:" % total_price))
            money = self.__input_number("总价%d元,请输入金额:" % total_price)
            if money >= total_price:
                print("购买成功,找回:%d元。" % (money - total_price))
                self.__controller.list_order.clear()
                break
            else:
                print("金额不足.")

    def main(self):
        """
            界面入口
        """
        while True:
            self.__select_menu()

    def __input_number(self, message):
        while True:
            try:
                number = int(input(message))
                return number
            except:
                print("输入有误")


try:
    view = ShoppingConsoleView()
    view.main()
except:
    print("对不起,我错了。")

 

上一篇:课设Day15—美工的一天


下一篇:DAY15 scanner对象