python-3.x - 我怎样才能让这些功能在我的菜单中工作
问题描述
我正在尝试创建一个程序来生成一个杂货清单,将易腐烂和不易腐烂的物品分开,打印出每个子类的小计,总税收总额和总总额,以及按需库存。我有下面的代码,但我无法让它正常工作......非常感谢任何和所有帮助。我对此仍然很陌生,并且正在努力学习。请温柔...
class Grocery_list():
def __init__(self,name,price):
""" Defines gorcery list item"""
self.name = name.title()
self.price = price
def __str__(self):
""" Returns formated item info """
return f"\nItem: {self.name}" f"\nPrice: ${self.price}"
def get_name(self):
""" Displays Item Name """
return f"Item name: {self.name}"
def get_price(self):
""" Display Item Price """
return f"\nYour item cost is {self.price}"
def is_perishable(self):
""" Defines if item is perishable """
raise NotImplementedError ('Not Implemented in Grocery_list')
def __add__(self, other):
self.price = self.price + other.price
subtotal = self.price
return "Subtotal: " + '$%.2f' % (subtotal)
class Perishable(Grocery_list):
""" Defines if item is perishable """
def __init__(self, name, price):
Grocery_list.__init__(self, name, price)
def is_perishable(self):
""" Defines if item is perishable """
perishable = input(f"\nIs your item perishable, yes or no: ")
perishable = perishable.lower()
if perishable == 'yes':
return True, f"{self.name} = perishable."
elif perishable == 'no':
return False, f"{self.name} = non-perishable."
else:
print ("\nI'm sorry, I didn't recognize your response. Please try again.")
class Non_perishable(Grocery_list):
""" Defines if item is non-perishable """
def __init__(self, name, price):
Grocery_list.__init__(self, name, price)
def is_perishable(self):
""" Defines if item is non perishable """
perishable = input(f"\nIs your item perishable, yes or no: ")
perishable = perishable.lower()
if perishable == 'yes':
return True, f"{self.name} = perishable."
elif perishable == 'no':
return False, f"{self.name} = non-perishable."
else:
print ("\nI'm sorry, I didn't recognize your response. Please try again.")
#============================================================================= ================================
# Everything below this line is the issue. I can't get the functions to work I need on function for each
# Menu item. (Adding items, Removing items, cart inventory, and getting a subtotal, tax amount, and total bill)
perishable = []
non_perishable = []
# This will work for the non_perishable list, but not the perishable. Don't know why
def create_grocery_item():
""" Create an Item for the grocery list """
name = input("\nItem Name: ")
price = input("\nItem Price: ")
perishable = input("Is this item perishable, yes or no? ")
perishable = perishable.lower()
if perishable == 'yes':
name = name.title()
item = Perishable(name,price)
perishable.append(item)
elif perishable == 'no':
name = name.title()
item = Non_perishable(name,price)
non_perishable.append(item)
else:
print ("Answer not recognized. Please try again.")
# I can't get this to work at all.
def remove_grocery_item():
name = input("What item would you like to remove?")
name = name.title()
if name in perishable:
del perishable [name]
print (f"\nItem {name} has been removed from your cart")
elif name in non_perishable:
del non_perishable [name]
print (f"\nItem {name} has been removed from your cart")
else:
print (f"\nI'm sorry, but {name} isn't in your cart. Please try again.")
# This one seems to work fine.
def print_cart():
""" Print Items in Cart """
print (f"The perishable items are: ")
for item in perishable:
print (f"Item:{item.name}" + f"/Price:${item.price}")
print (f"\nThe non-perishable items are: ")
for item in non_perishable:
print (f"Item:{item.name}" + f"/Price:${item.price}")
# Honestly, I am not even sure where to start here....I can't figure out if I should create a seperate function
# for this, or if I should make a method inside the parent class. I'm supposed to have it add up the subtotal
# for each category (perishable and non_perishable), print those out seperately followed by the tax for and the
# overall bill total.
def check_out():
sum = 0
for item in perishable:
sum += item
print (sum)
for item in non_perishable:
sum += item
print (sum)
# Here is the code for the menu options. This seems to work fine. I just need to figure out the functions
# to plug in....
ans=True
while ans:
print("""
1. Add item to cart
2. Remove item from cart
3. Show all items in cart
4. Check out
5. Exit
""")
ans = input("Please select an option from the list: ")
if ans == '1':
create_grocery_item()
elif ans == '2':
remove_grocery_item()
elif ans == '3':
print ("\nHere is your current cart: ")
print_cart()
elif ans == '4':
print ("\nYour total bill is: ")
check_out()
elif ans == '5':
print ("\nThank you for shopping with us. Goodbye!")
ans = None
else:
print ("\nI'm sorry, that isn't a valid selection. Please try again")
解决方案
您可能应该有一个class Item
, 具有一个属性来判断一个Item
是否易腐烂,以及一个GroceryList
是 的集合的类item
,配备适当的方法:
像这样的东西,也许:
[编辑]:
我为每个item
类别添加了一个类,所以现在每个类别都有一个不同的type
; 它们都继承自提供所有功能的基类。基类可以(但不是必须)继承自abc.ABC
; IDK 如果允许你导入模块,所以我把它放在一边。
在实例化之外,其余代码保持不变,输出也是如此。
class AbstractItem:
def __init__(self, name, price):
""" Defines gorcery list item"""
self.name = name
self.price = price
def __str__(self):
""" Returns formated item info """
return f"Item: {self.name}, Price: ${self.price}"
class PerishableItem(AbstractItem):
@property
def perishable(self):
return True
class NonPerishableItem(AbstractItem):
@property
def perishable(self):
return False
class GroceryList:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def get_perishables(self):
perishables = []
for item in self.items:
if item.perishable:
perishables.append(item)
return perishables
def get_non_perishables(self):
non_perishables = []
for item in self.items:
if not item.perishable:
non_perishables.append(item)
return non_perishables
def __str__(self):
res = ['Shopping List', '\n']
res += ['\t', 'Perishables:\n']
for item in self.get_perishables():
res.append('\t\t' + str(item) + '\n')
res += ['\t', 'Non Perishables:\n']
for item in self.get_non_perishables():
res.append('\t\t' + str(item) + '\n')
return ''.join(res)
carrots = PerishableItem('Carrots', 12.5)
whiskey = NonPerishableItem('Whiskey', 45)
butter = PerishableItem('Butter', 22)
grocery = GroceryList()
grocery.add_item(carrots)
grocery.add_item(whiskey)
grocery.add_item(butter)
print(grocery)
输出:
Shopping List
Perishables:
Item: Carrots, Price: $12.5
Item: Butter, Price: $22
Non Perishables:
Item: Whiskey, Price: $45
推荐阅读
- ios - 如何检测设备是否在 iOS 中重新启动?
- c# - 如何在 EF Core 中包含导航属性
- go - 如何使用 Vimeo 上传 API 包含元数据
- active-directory - LDAP 查询 Active Directory 安全组中的成员身份
- c# - 了解 Select 操作 | Azure Cosmos DB 表 API
- python - 我在 Django 电子商务重复条目中的 /cart/ 处收到 IntegrityError
- matlab - 如何在 MATLAB 中的信号中添加 x % 噪声?
- c# - VSCode 无法运行 .net core api
- javascript - 如何通过推送迭代和追加数组的字符
- javascript - 如何在打字稿数组中找到第一个非空值?