“'type' 对象不可订阅”使用数据类

"'type' object is not subscriptable" working with dataclasses

尝试将 csv 文档中的数据输入到数据类中。

from dataclasses import dataclass
@dataclass

class deck:
    name:str = ''
    length:float = 0.0
    width:float = 0.0
    cost:int = 0

def read(deck):
    with open("Deckingcsv.csv", "r") as d:
        line = d.readline().rstrip('\n') 
        counter = 0
        while line:
            items = line.split(',') 
            print(items)
            deck[counter].name = items[0] 
            deck[counter].length = items[1]
            deck[counter].width = items[2]
            deck[counter].cost = items[3]
            line = d.readline().rstrip('\n') #separates another line
            counter += 1
    return deck


read(deck)
print(deck)

CSV 文档是:

Themon,3.2,2.3,450
Larrec,3.4,3,700
Medrec,2.1,2,500
Parallel,5,4,825
Suncatch,3,3,400
Chantran,9,6,975

但是,这将返回此错误:TypeError:'type' 对象不可订阅,第 18 行 不能完全弄清楚这个错误是从哪里引起的,任何帮助将不胜感激:)

deck 是一个 class。如果你想创建一副物品,试试这个:

from dataclasses import dataclass
@dataclass

class Item:
    name:str = ''
    length:float = 0.0
    width:float = 0.0
    cost:int = 0

def read(deck):
    with open("Deckingcsv.csv", "r") as d:
        line = d.readline().rstrip('\n') 
        counter = 0
        while line:
            items = line.split(',') 
            print(items)
            item = Item(items[0],items[1],items[2],items[3]
            deck.append(item)
            line = d.readline().rstrip('\n') #separates another line
            counter += 1
    return deck

deck = []
read(deck)
print(deck)