2014-02-20 31 views
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 

我猜是它​​不看,我已经分配给该项目的值,如果是这样的错误情况下,我如何得到它?

回答

0

其他人指出你的错误,但其他的错误是你的buy调用需要在对象的一个​​实例上完成,而不是在类本身上完成。换句话说,您现在正在零售上执行购买,您需要在类的实例(对象)上执行它。

我有另一个建议来帮助组织你的代码。使用字典将键映射到各种对象,使循环更清晰。把所有一起(和其他一些检查),这里是你的类的更新版本:

class Retail(object): 

    def __init__(self, price, unitsOnHand, description): 
     self.price = price 
     self.unitsOnHand = unitsOnHand 
     self.description = description 

    def buy(self): 
     if self.unitsOnHand == 0: 
      print('Sorry, we are all out of {} right now.'.format(self.description)) 
      return 
     print("How many are you buying? We have {}".format(self.unitsOnHand)) 
     quant = int(input("Amount: ")) 
     while quant > self.unitsOnHand: 
      print('Sorry, we only have {} left'.format(self.unitsOnHand)) 
      quant = int(input("Amount: ")) 
     self.unitsOnHand -= quant 
     subto = self.price * quant 
     total = subto * 1.08 
     print("There are now {} left".format(self.unitsOnHand)) 
     print("The total price is ${}".format(total)) 
     return 

stock = {} 
stock['box'] = Retail(4.95, 20, "Boxes") 
stock['paper'] = Retail(1.99, 50, "Big Stacks of Paper") 
stock['staples'] = Retail(1.00, 200, "Staples") 

print("Which are you buying? {}".format(','.join(stock.keys()))) 
ioi = input("Please use the exact word name: ") 

while ioi not in stock: 
    print("Sorry, we do not have any {} right now.".format(ioi)) 
    print("Which are you buying? {}".format(','.join(stock.keys()))) 
    ioi = input("Please use the exact word name: ") 

stock[ioi].buy() 
+0

感谢。我也意识到我应该在'buy'中应用self.price。 – user3300735