python - 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"))
解决方案
在购物车中添加没有名称属性的项目。相反,您应该附加 obj ,因为您需要对象的 name 属性。更改item
为obj
将修复它并消除错误。
作为警告,请考虑将设置shopping_cart
作为实例变量传递ShoppingCart
,以及将列表Products
作为参数传递。我认为这将使您的代码更好,以使传递范围和了解变量的位置更容易。现在,您将它们全部设为只读,并且它们不属于ShoppingCart
.
推荐阅读
- c# - Blazor 将字符串发布到 API 获取 NULL
- java - 生产者和消费者没有按顺序打印答案
- python - pygame.draw.rect 和 screen_surface.blit() 有什么区别?
- c++ - 即使链表中只剩下一个节点,如何按值删除链表中的节点
- java - 使用多个列表保留所有值
- python - 我怎样才能摆脱 NaN 的预测和损失?带有 Keras 的 LSTM
- labview - 通过 LabVIEW 使用 https 进行身份验证
- mqtt - 为什么我对公共 MQTT 代理的订阅只收到我自己的消息?
- django - 如何通过 url 访问 django 中的 txt 文件以进行验证
- html - 在 HTML 中访问文件夹结构中的图像