python 基础 类与对象的练习

创建ComputerShop类,参数:list列表,存储内容有库存、品牌、价格(例如:list = [{‘count’:11,'brand
':‘拯救者’,‘price’:5999},{‘count’:21,‘brand’:‘外星人’,‘price’:7999]),money为用户开店进货后剩余金额,创建对象时需要指定该金额。
方法有:
1、查找商品,让用户输入指定品牌,查找到后打印该品牌电脑的信息;
2、售卖商品,用户输入商品名称后,在库存中查找信息,判断库存,然后卖出(默认一台一台的卖),卖出结果为库存该商品-1,店铺余额money增加;
3、商品进货,输入进货名称,进货价为商品价格-1000,判断店铺金额是否满足进货金额,不满足重新输入,满足后,店铺余额减少,指定商品数量增加
4、打印店铺信息,将剩余商品的名称、价格、库存以及店铺余额打印出来
class ComputerShop:

def __init__(self,list,money):
	self.list = list
	self.money = money

def __str__(self):
	msg = ""
	for dict in list:
		for key in dict.keys():
			if key == 'brand':
				msg += "品牌:"+dict[key]+','
			if key == 'price':
				msg += "单价:%d"%dict[key]+','
			if key == 'count':
				msg += "库存:%d"%dict[key]+','
		msg = msg.strip(',')
		msg+='\n'
	msg += '店铺余额:%d'%self.money
	return msg

def search_computer(self):
	a = 1#假设当前查找的电脑不存在
	print('请输入要查找的电脑品牌:')
	brand = input()
	for dict in list:
		if brand in dict.values():
			print('您要查找的品牌为%s,单价为%d'%(dict['brand'],dict['price']))
			a = 2
			break
	if a == 1:
		print('对不起,本店没有您要的电脑品牌!')


def sell_computer(self):
	isExist = False
	print('请输入您要购买的电脑品牌:')
	brand = input()
	for dict in list:
		if brand in dict.values():
			print('您要查找的品牌为%s,单价为%d'%(dict['brand'],dict['price']))
			count = dict['count']
			if count == 0:
				print('对不起,该品牌的电脑暂时无货')
			else:
				print('恭喜您购买成功,付款%d元'%dict['price'])
				dict['count'] = count - 1
				self.money += dict['price']
				isExist = True
				break
	if not isExist:
		print('对不起,本店没有您要的电脑品牌!')

def buy_computer(self):
	canBuy = False
	print('请输入您要进货的电脑品牌:')
	brand = input()
	for dict in list:
		if brand in dict.values():
			canBuy = True
			break
	if canBuy:
		number = int(input('请输入进货数量:'))
		for dict in list:
			if brand in dict.values():
				totalPrice = (dict['price'] - 1000) * number
				print('总价为:%d'%totalPrice)
				break
		if totalPrice > self.money:
			print('对不起,您的金额不足!')
		else:
			self.money -= totalPrice
			for dict in list:
				if brand in dict.values():
					dict['count'] += number
					break
	else:
		print('您要进货的品牌不再授权范围内!')

list = [
{‘count’:11,‘brand’:‘拯救者’,‘price’:5999},
{‘count’:21,‘brand’:‘外星人’,‘price’:7999},
{‘count’:20,‘brand’:‘飞行堡垒’,‘price’:4999}]

shop = ComputerShop(list,20000);

isExit = True;
while isExit:
num = int(input(‘请输入用户类型:’))
if num == 1:
print(‘欢迎光临本小店,请选择您要进行的操作:’)
while True:
print(‘1、查找商品’)
print(‘2、购买商品’)
print(‘3、退出’)
number = int(input())
if number == 1:
shop.search_computer()
elif number == 2:
shop.sell_computer()
else:
break
if num == 2:
print(‘欢迎光临本小店,请选择您要进行的操作:’)
while True:
print(‘1、店铺进货’)
print(‘2、查看店铺信息’)
print(‘3、退出’)
number = int(input())
if number == 1:
shop.buy_computer()
elif number == 2:
print(shop)
else:
isExit = False
print(‘Goodbye~~~~’)

猜你喜欢

转载自blog.csdn.net/cc576795555/article/details/83243921
今日推荐