python全局名称不是使用类定义的

2024-05-16 20:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个类的客户购物车,所以我创建了一个类的产品,然后购物篮与方法添加,删除和空篮子。 现在我想计算一篮子有大量报价的总价格。 我的问题是'total'方法,错误是'global name x is not defined'。你知道吗

我的问题是我需要编码,因为cart中的东西是产品类实例的name属性。我想不出另外一种方法来将产品添加到“购物车”或列表中,所以希望我没有犯错误。我不明白为什么这里有一个错误,但在我使用的additems方法中没有项目.数量. 你知道吗

我猜不同的是,item是函数域的一部分,而x不是。我不认为我的total方法需要任何其他输入。我只需要自我,因为每个自我都有一个篮子,这就是我所需要的。你知道吗

谢谢你的帮助

class products:
  def __init__(self,name,price,quantity):
    self.price=price
    self.quantity=quantity
self.productname=name



class ShoppingBasket:
  def __init__(self,name,basket=[]):
    self.name=name
    self.basket=basket[:]






def additems(self,*items):

for item in items: 

    if item.quantity>0:

      self.basket.append(item.productname)
      item.quantity-=1
      print  "%s has been added to %s's basket"%(item.productname, self.name)
    else:
      print "sorry item is not in stock"



  def removeitems(self,*items):

for item in items:
  if item.productname in self.basket:
    self.basket.remove(item.productname)
    item.quantity+=1

    print "%s has been removed from %s's basket"%(item.productname,self.name) 
  else: print "not in basket"


  def empty(self):
    self.basket[:]=[]
    print "%s's basket is empty"%(self.name)

  def total(self):
    total=0

    for x.productname in self.basket:
      z=[s for s in self.basket if s==x.productname ]
      if len(z)%2==0: 
        price=x.price*(len(z)/2)
      else: 
        price=x.price*(len(z)//2)+item.price
      total+=price
    return total

Tags: 方法nameinselfforifdefitems
2条回答

我已经找到了一个办法让它发挥作用。我定义了一个新属性:secretbasket来保存所有类实例,basket保存它们的名称(为了消费者的利益)。我的函数现在可以工作并处理BOGOF!你知道吗

def total(self):
    total=0
    for x in self.secretbasket:
        z=[s for s in self.secretbasket if s==x]

        if len(z)%2==0:
            price=x.price*(len(z)/2)
            self.secretbasket=[s for s in self.secretbasket if s!=x ]
        else: 
            price=x.price*(len(z)//2)+x.price
            self.secretbasket=[s for s in self.secretbasket if s!=x ]
        print price
        total+=price
    return total

不能在这样的循环中迭代属性

for x.productname in self.basket:

你必须分配对象,然后得到它。你知道吗

for x in self.basket:
    z=[s for s in self.basket if s==x.productname]

我没有遵循这个逻辑,但这似乎是一个非常低效的方式来合计篮子里的所有产品。你知道吗

例如,这将添加篮子中项目的所有价格

return sum(x.price for x in self.basket) 

注意:item在循环中也是未定义的

为了实施BOGOF提议,我建议尝试不要在篮子中添加已经存在的物品,尽管如果购买同一物品中的两件以上,效果可能会很差。
我的观点是,只需要一行就可以计算出总数,如图所示。在将项目添加到篮子中时,可以执行仅将奇数个项目保留为总数的逻辑

相关问题 更多 >