1 importsys2 importcopy3
4
5 classProduct:6 def __init__(self, pid, name, price, count):7 self.pid =pid8 self.name =name9 self.price =price10 self.count =count11
12 def __str__(self):13 return "id>>" + str(self.pid) + "\tname>>" + self.name+"\tprice>>" + str(self.price) + "\tcount>>" +str(self.count)14
15
16 classProductList:17 #输入列表,抓成以id为key的字典,便于以后查找
18 def __init__(self, products=[]):19 self.prod_list =dict()20 for product inproducts:21 self.prod_list[product.pid] =product22
23 defminus(self, productId, num):24 if productId inself.prod_list:25 if self.prod_list[productId].count >num:26 self.prod_list[productId].count -=num27 returnTrue28 elif self.prod_list[productId].count ==num:29 self.prod_list.pop(productId)30 returnTrue31 else:32 print("库存不够,请重新选择数量")33 returnFalse34 else:35 print("本仓库没有此件商品,请重新选择")36
37 def add(self, product, num=1):38 if product.pid inself.prod_list:39 self.prod_list[product.pid].count +=num40 else:41 new_product =copy.deepcopy(product)42 new_product.count =num43 self.prod_list[new_product.pid] =new_product44
45 defprint_all_product(self):46 for key inself.prod_list:47 print(self.prod_list[key])48
49
50 classShopping:51 @classmethod52 defget_salary(cls):53 salary = input("请输入您购买卡的余额:")54 if notsalary.isdecimal():55 print("您输入的卡的余额不是数值型,请重新输入")56 returnShopping.get_salary()57 else:58 returnint(salary)59
60 def __init__(self, sell_product=[]):61 self.salary =Shopping.get_salary()62 self.sell_product =ProductList(sell_product)63 self.buy_product =ProductList()64
65 defbuy_some_product(self):66 self.sell_product.print_all_product()67 select_product = input("请输入您的产品编码:")68 product_num = input("请输入商品的数量:")69 ifproduct_num.isdigit():70 product_num =int(product_num)71 else:72 print("数量必须是数字!")73 self.buy_some_product()74 #如果够支付,则工资减少,同时buy_product增加一个商品
75 ifself.is_afford(select_product, product_num):76 self.buy_product.add(self.sell_product.prod_list[select_product], product_num)77 self.salary -= self.sell_product.prod_list[select_product].price*product_num78 self.sell_product.minus(select_product, product_num)79 print("您当前购买商品如下:")80 self.buy_product.print_all_product()81 print("您的余额是 %s 元" %self.salary)82 else:83 print("您的余额不足,请重新选择")84
85 #判断当前的工资余额是否够支付产品
86 defis_afford(self, procudtId, product_num):87 if type(procudtId) ==int:88 procudtId =str(procudtId)89 if self.salary >= self.sell_product.prod_list[procudtId].price *product_num:90 returnTrue91 else:92 returnFalse93
94 defselect_process(self):95 whileTrue:96 selector = input("""
97 请输入您的选择?98 购买(b)99 退出(q)100 """)101 if selector == 'b':102 self.buy_some_product()103 else:104 print("您购买了如下商品")105 self.buy_product.print_all_product()106 print("您的余额是 %s 元" %self.salary)107 print("欢迎您下次光临")108 sys.exit(0)109
110
111
112 if __name__ == '__main__':113 #测试初始化产品列表的信息的功能
114 init_product=[Product('1', 'bike', 100, 10), Product('2', 'ipad', 3000, 3), Product('3', 'paper', 500, 30)]115 shop =Shopping(init_product)116 shop.select_process()