1. 程式人生 > >python 基礎 類與物件的練習

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~~~~’)