3
所以首先我要创建一个类,它包含一个项目的名称,价格和数量。然后,我想创建一个函数,在买入数量后扣除销售给买方的数量,然后计算总价格。从类列表中挑选Python项目
现在要添加上,我试图让用户从项目列表中选择。
问题在于,我似乎在程序开始运行“购买”功能的时候出现错误。
class Retail:
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy (self):
print ("How many are you buying?")
quant = int(input("Amount: "))
unitsOnHand -= quant
subto = price * quant
total = subto * 1.08
print ("There are now ", unitsOnHand, " left")
print ("The total price is $", total)
box = Retail(4.95, 20, "Boxes")
paper =Retail(1.99, 50, "Big Stacks of Paper")
staples =Retail(1.00, 200, "Staples")
ilist = (box, paper, staples)
print ("Which are you buying? ", [box.description, paper.description, staples.description])
ioi = input("Please use the exact word name: ")
if ioi == 'box':
Retail.buy(ilist[0])
elif ioi == 'paper':
Retail.buy(ilist[1])
elif ioi == 'staples':
Retail.buy(ilist[2])
我得到当我试图运行它是
Traceback (most recent call last):
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 22, in <module>
Retail.buy(ilist[0])
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 9, in buy
unitsOnHand -= quant
UnboundLocalError: local variable 'unitsOnHand' referenced before assignment
我猜是它不看,我已经分配给该项目的值,如果是这样的错误情况下,我如何得到它?
感谢。我也意识到我应该在'buy'中应用self.price。 – user3300735