Python class bug



我的remove和new quantity方法不工作,我不知道为什么。下面是我的代码:

# Type code for classes here
class ItemToPurchase():
def __init__(self):
self.item_description = 'none'
self.item_name = 'none'
self.item_price= 0
self.item_quantity = 0
def print_item_description(self):
print(f'{self.item_name}: {self.item_description}')
class ShoppingCart():
def __init__(self, customer_name='none', current_date='January 1, 2016'):
self.customer_name = customer_name
self.current_date = current_date
self.items = []
def add_item(self, item ):
''' Adds an item to cart_items list. Has parameter of type ItemToPurchase. Does not return anything. '''
self.items.append(item)
def remove_item(self, item ):
''' Removes item from cart_items list. Has a string (an item's name) parameter. Does not return anything.
If item name cannot be found, output this message: Item not found in cart. Nothing removed. '''
delete = False
for item in self.items:
if self.items == item:
to_be_deleted = self.items[item]
delete = True
else:
print("Item not found in cart. Nothing removed.")
if delete == True:
del self.items[to_be_deleted]

def modify_item(self, item, new_quantity):
'''Modifies an item's quantity. Has a parameter of type ItemToPurchase. Does not return anything.
If item can be found (by name) in cart, modify item in cart.'''
if item in self.items:
item.quantity = new_quantity
else:
print("Item not found in cart. Nothing modified.")
def get_num_items_in_cart(self):
'''Returns quantity of all items in cart. Has no parameters.'''
num_items = 0
for item in self.items:
num_items += item.item_quantity
#return the num_Items
return num_items
def get_cost_of_cart(self):
'''Determines and returns the total cost of items in cart. Has no parameters.'''
return sum(item.item_price * item.item_quantity for item in self.items)
def print_total(self):
'''Outputs total of objets in cart.
If cart is empty, outputs this message: CART IS EMPTY.'''
print(f"{self.customer_name}'s Shopping Cart - {self.current_date}")
number_items = self.get_num_items_in_cart()
print(f'Number of Items: {number_items}n')
total_cost = self.get_cost_of_cart()
if total_cost == 0:
print("SHOPPING CART IS EMPTYn")
print(f'Total: ${total_cost}')
return False
else:
for item in self.items:
item_cost = item.item_quantity * item.item_price
print(f'{item.item_name} {item.item_quantity} @ ${item.item_price} = ${item_cost}')
print()
total_cost = self.get_cost_of_cart()
print(f'Total: ${total_cost}')
def print_descriptions(self):
''' Outputs each item's description'''
print(f"{self.customer_name}'s Shopping Cart - {self.current_date}n")
for item in self.items:
print("Item Descriptions")
print(f'{item.item.name}: {item.item_description}')
def print_menu():
print("MENUna - Add item to cartnr - Remove item from cartnc - Change item quantityni - Output items' descriptionsno - Output shopping cartnq - Quitn")

def execute_menu(choice , shopping_cart):
if choice == "o":
print("OUTPUT SHOPPING CART")
shopping_cart.print_total()

elif choice == "i":
print("OUTPUT ITEMS' CART")
shopping_cart.print_descriptions()

elif choice == "a":
print("ADD ITEM TO CARTnEnter the item name:")
item_name = input()
print("Enter the item description:")
item_description = input()
print("Enter the item price:")
item_price = int(input())
print("Enter the item quantity:")
item_quantity = int(input())
New_item = ItemToPurchase()
New_item.item_name = item_name
New_item.item_price = item_price
New_item.item_quantity = item_quantity
New_item.item_description = item_description
shopping_cart.add_item(New_item)

elif choice =="r":
print("REMOVE ITEM FROM CARTnEnter name of item to remove:")
removed_item = input()
shopping_cart.remove_item(removed_item)
elif choice == "i":
'''Implement Change item quantity menu option in execute_menu(). Hint: Make new ItemToPurchase object before using ModifyItem() method. '''
print("CHANGE ITEM QUANTITYnEnter the item name:")
Item = ItemToPurchase()
Item.item_name = input()
print("Enter the new quantity:")
Item.item_quantity = input()
if __name__ == "__main__":
shopping_cart = ShoppingCart()
print("Enter customer's name:")
shopping_cart.customer_name = input()
print("Enter today's date:")
shopping_cart.current_date = input()
print()
print(f"Customer name: {shopping_cart.customer_name}nToday's date: {shopping_cart.current_date}")
print()

print_menu()
print("Choose an option:")
while True:
choice = input()
if choice in "arcioq":
if choice == 'q':
break
else:
execute_menu(choice, shopping_cart)
print()
print_menu()
print("Choose an option:")



我认为与删除我比较错误的数据类型,我似乎不能使它工作。顺便说一下,函数名不能改变,我不能添加任何新的函数。我只能使用预先存在的方法、类和函数的文档字符串

您没有正确使用del。我想你把del和列表的.remove()方法混淆了。

del self.items[to_be_deleted]没有意义。self.items是一个列表,列表索引必须是整数。但to_be_deleted不是整数;它是列表中的一个实际项目。

如果您想使用del,则需要删除列表项的整数索引。

但是由于您拥有实际对象本身,因此可以调用self.items.remove(),它将实际对象作为参数。

最新更新