class Goods(object):
def __init__(self,id,name,price):
self.id = id
self.name =name
self.price =price
def __str__(self):
info = "編號:%s\t商品名稱:%s\t\t價格:%d"%(self.id,self.name,self.price)
return info
class ShopManager(object):
def __init__(self,path):
# path:表示讀取檔案的路徑 shopdic:表示存放記憶體的容器
self.path = path
self.shopdic = self.readFileToDic()
def readFileToDic(self):
# 讀取檔案,寫入到字典中
f = open(self.path, 'a+', encoding='utf-8')
clist = f.readlines()
f.close()
index = 0
shopdic = {}
while index < len(clist):
# 將每一行的字串進行分割,存放到新的串列中
ctlist = clist[index].replace('\n', "").split("|")
# 將每行的內容存放到一個物件中
good = Goods(ctlist[0],ctlist[1],int(ctlist[2]))
# 將對向存放到集合中
shopdic[good.id] = good
index = index + 1
return shopdic
def writeContentFile(self):
# 將記憶體當中的資訊寫入到檔案當中
str1 = ''
for key in self.shopdic.keys():
good = self.shopdic[key]
ele = good.id+"|"+good.name+"|"+str(good.price)+"\n"
str1 = str1 + ele
f = open(self.path, 'w', encoding='utf-8')
f.write(str1)
f.close()
def addGoods(self):
# 添加商品的方法
id = input("請輸入添加商品編號:>")
if self.shopdic.get(id):
print("商品編號已存在,請重新選擇!")
return
name = input("請輸入添加商品名稱:>")
price = int(input("請輸入添加商品價格:>"))
good = Goods(id,name,price)
self.shopdic[id] = good
print("添加成功!")
def deleteGoods(self):
# 洗掉商品的方法
id = input("請輸入洗掉商品編號:>")
if self.shopdic.get(id):
del self.shopdic[id]
print("洗掉成功!")
else:
print("商品編號不存在!")
def showGoods(self):
# 展示所有商品資訊
print("="*40)
for key in self.shopdic.keys():
good = self.shopdic[key]
print(good)
print("="*40)
def adminWork(self):
info = """
==========歡迎進入好海哦購物商場==========
輸入功能編號,您可以選擇以下功能:
輸入“1”:顯示商品的資訊
輸入“2”:添加商品的資訊
輸入“3”:洗掉商品的資訊
輸入“4”:退出系統功能
==========================================
"""
print(info)
while True:
code = input("請輸入功能編號:>")
if code == "1":
self.showGoods()
elif code == "2":
self.addGoods()
elif code == "3":
self.deleteGoods()
elif code == "4":
print("感謝您的使用,正在退出系統!!")
self.writeContentFile()
break
else:
print("輸入編號有誤,請重新輸入!!")
def userWork(self):
print(" ==============歡迎進入好海哦購物商場==============")
print("您可輸入編號和購買數量選購商品,輸入編號為n則結賬")
self.showGoods()
total = 0
while True:
id = input("請輸入購買商品編號:>")
if id == "n":
print("本次購買商品共消費%d元,感謝您的光臨!"%(total))
break
if self.shopdic.get(id):
good = self.shopdic[id]
num = int(input("請輸入購買數量:>"))
total = total+good.price*num
else:
print("輸入商品編號有誤,請核對后重新輸入!")
def login(self):
# 登錄功能
print("==========歡迎登錄好海哦購物商場==========")
uname = input("請輸入用戶名:>")
password = input("請輸入密碼:>")
if uname == "admin":
if password == "123456":
print("歡迎您,",uname,"管理員")
self.adminWork()
else:
print("管理員密碼錯誤,登錄失敗!")
else:
print("歡迎你,%s用戶"%(uname))
#執行用戶的購買功能
self.userWork()
if __name__ == '__main__':
shopManage = ShopManager("shop.txt")
shopManage.login()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/83674.html
標籤:新技術前沿
