为了修复NameError(名称未定义的问题),我使用了像这样的全局关键字,但我不认为这是一个很好的解决方案。我想把代码的最后一部分放到一个函数(main())中,然后再次使用purchase_item函数发生未定义的错误,有人可以帮我改进这段代码吗?
from RetailItem import RetailItem
类CashRegister:
global Item_List
global Cashier_List
global total
Item_List = [ RetailItem("Item 1","Jacket", 12, 59.95),
RetailItem("Item 2", "Designer Jeans", 40, 34.95),
RetailItem("Item 3", "Shirt", 20, 24.95) ]
Cashier_List = []
total = 0
def purchase_item(RetailItem):
global Cashier_List
Cashier_List.append(RetailItem)
def get_total():
global Cashier_List
global total
for o in Cashier_List:
total += o.getPrice()
return total
def show_items():
global Cashier_List
for o in Cashier_List:
print(o)
def clear():
global Cashier_List
del Cashier_List[:]
print("Here are available items:")
for o in Item_List:
print(o)
while True:
x = input("Select items by number to buy or enter \"n\" to finish shopping: ")
if x != "n":
try:
purchase_item(Item_List[int(x)-1])
print("ADDED!")
except ValueError:
print("Invalid number, try again!")
except IndexError:
print("Invalid number, try again!")
else:
break
print("......The total price is ${:0.2f}\n......This is your checkout items:".format(get_total()))
show_items()