Python从类列表中选择项目

时间:2014-02-20 05:05:27

标签: python list function class object

所以首先我要创建一个类,其中包含项目的名称,价格和数量。然后我想制作一个功能,在他们输入购买金额后扣除卖给买家的数量,然后计算总价。

现在要添加,我试图让用户从项目列表中进行选择 问题是,似乎我似乎在程序开始运行“购买”功能时遇到错误。

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

我猜是它没有看到我已经分配给该项目的值,如果是这种情况,我该如何获取它?

1 个答案:

答案 0 :(得分: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()