【发布时间】:2014-03-20 20:28:24
【问题描述】:
所以首先我尝试创建一个类,其中包含可用的项目名称、价格和数量。然后我想做一个函数,在买家输入他们购买的数量后,扣除出售给他们的数量,然后计算总价。
现在要补充一点,我试图让用户从项目列表中进行选择。
问题是我似乎在程序开始运行“购买”功能时遇到了错误。
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
我猜是它看不到我已经分配给该项目的值,如果是这样,我该如何得到它?
【问题讨论】:
标签: python list function class object