首页 > 解决方案 > python错误-打印(i.price)AttributeError:'str'对象没有属性'price'-抱歉这么长的问题,但希望提供所有信息

问题描述

我正在尝试在 python 中为在线玩具商店创建一个面向对象的程序。

我有几个不同的类,例如 shopping_cart 和 products。

我试图创建一个计算购物车总价格的函数,但不断收到以下错误:

AttributeError:“str”对象没有属性“price”

#Creating shopping cart class
from products import *

class ShoppingCart:
def __init__(self, itemQuantity, productID, itemPrice, totalPrice, supplier):
    self.itemQuantity = itemQuantity
    self.productID = productID
    self.itemPrice = itemPrice
    self.totalPrice = totalPrice
    self.supplier = supplier

def displayCart(self):
    print()
    if shopping_cart == []:
        print(''' Your Shopping Cart is Empty''')
    else:
        for i in shopping_cart:
            print(i)

def add_products(self):
    item = input('''Please enter the item you wish to add to your shopping cart''')
    for obj in products:
        if item in obj.name:
            shopping_cart.append(item)
            print(item + " has been added to your cart")
            break
        else:
            print("Error this product has not been found ")

def totalprice(self):
    total = 0
    for i in shopping_cart:
        print(i.price)
        cost = i.price
        print('Your total is' + str(cost))
    shopping_cart = []

def totalprice 函数存在问题,与它没有字符串对象有关,这是否与产品类相关联,该产品类位于不同的文件中,如下所示

#creating store products
from shopping_cart import *

class Products:
def __init__(self, name, id, price, quantity, supplier):
    self.name = name
    self.id = id
    self.price = price
    self.quantity = quantity
    self.supplier = supplier

  def listProducts(self):
      print("Store Products:")

  for obj in products:
      print(obj.name + ' £' + obj.price)


  def addProduct(self, name, id, price, quantity, supplier):
      self.name = name
      self.id = id
      self.price = price
      self.quantity = quantity
      self.supplier = supplier

      addproduct = input("Please select the product you wish to add to your Shopping Cart:")
      products.append(Products('name', id, 'price', quantity, "supplier"))

      def removeProduct(self):
          item = input("Please select which product to remove:")
          products.remove(item)
          print(item + " has been removed")

    products=[]   
    products.append(Products('Playdough', 2212,'15.00', 100, "B"))
    products.append(Products('Robot', 2213,'20.00', 100, "B"))
    products.append(Products('Book', 2214,'05.00', 100, "B"))

标签: python

解决方案


在购物车中添加没有名称属性的项目。相反,您应该附加 obj ,因为您需要对象的 name 属性。更改itemobj将修复它并消除错误。

作为警告,请考虑将设置shopping_cart作为实例变量传递ShoppingCart,以及将列表Products作为参数传递。我认为这将使您的代码更好,以使传递范围和了解变量的位置更容易。现在,您将它们全部设为只读,并且它们不属于ShoppingCart.


推荐阅读