我正在嘗試使用程式方法而不是面向物件的方法在 Python 中創建一個商店,然后我創建了這個函式,該函式使用商店庫存讀取我的 CSV 檔案,除了包含“可用現金”的 CSV 檔案的第一行商店。
然后我試圖訪問價格和數量,但出現錯誤:
p=(row[0], float(row[1]))
IndexError: list index out of range
這是我的參考代碼:
def createAndStockShop():
s=Shop()
with open("Stock.csv")as csv_file:#reading our stock file
csv_reader=csv.reader(csv_file,delimiter=',')#creating csv reader variable setting up delimiter as ","
first_row=next(csv_reader)
s.cash=(first_row[0])#extracting shop cash from first row of the file
for row in csv_reader:#using for loop to go through the file
p=(row[0], float(row[1]))
ps=ProductStock(p,float(row[2]))
s.stock.append(ps)
print(ps)
return s#returning shop
作為參考,這是檔案“Stock.csv”的外觀: 我正在使用此代碼打開并包含我的股票的 csv 檔案
此外,這些是我為 Product stock 和 shop 創建的類,以提供更多背景資訊:
@dataclass #Creating first data class for Products in shop
class Product:
name: str #values are "name" as string and price as float to include decimals
price: float = 0.0
@dataclass #Creating data class for the stock in shop
class ProductStock:
product:Product
quantity:int
@dataclass #Dataclass for shop, values cash as a float and stock as list
class Shop():
cash: float = 0.0
stock: List[ProductStock] = field(default_factory=list)
uj5u.com熱心網友回復:
非常感謝你們,最后我按照你的建議洗掉了檔案中的空行,并且成功了!!非常感謝。但是現在告訴我一個不同的錯誤:'''" 第 126 行,如果 item.product.name == prod.product.name 和 item.quantity <= prod.quantity:#checking if item name in list matching the有庫存的名稱 AttributeError: 'tuple' 物件沒有屬性 'name'"
''' 我理解它指的是這段代碼:
#defining method to check the shop stock:
def checking_stock(c, s): #parameters for this function will be "c" ( customer) and s (shop)
for item in c.shopping_list:#looping through the items in customer shopping list
for prod in s.stock:
if item.product.name == prod.product.name and item.quantity <= prod.quantity:#checking if item name in list matches the name in stock
#also if quantity needed is less than the amount or product in stock
print(item, item.quantity, prod.quantity)#if this is the case, print item quantity and agree with the purchase
print("\nPerfect! you can proceed.")
elif item.product.name == prod.product.name and item.quantity > prod.quantity:#else if the product amount requested by client is bigger than stock
print(f"Hey! So sorry! We do not have enough stock of: {item.product.name}, please select a different amount.")#printing error message
main()
如之前所示,我為 Product 創建的類有一個屬性名稱:
@dataclass #Creating first data class for Products in shop
class Product:
name: str #values are "name" as string and price as float to include decimals
price: float = 0.0
和這個有關嗎?太感謝了。
uj5u.com熱心網友回復:
根據您發布的影像...第 9,10 行是空行。洗掉它們并重試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/386375.html
標籤:Python 文件 python-数据类
