gpt4 book ai didi

python - 如何将文件数据存储为类对象?

转载 作者:行者123 更新时间:2023-12-04 15:11:51 26 4
gpt4 key购买 nike

<分区>

假设我们有一个类:

class Car:
def __init__(self, model, name, price):
self.model = model
self.name = name
self.price = price

还有一个 .txt 文件:

201    BMW              1.2
202 Mercedes Benz 1.6

是否可以在 model 中存储 '201' 和 '202',在 name 中存储 'BMW' 和 'Mercedes Benz',在 中存储 1.2 和 1.6价格 无需手动...

    car1 = Car('201', 'BMW', 1.2)
car2 = Car('202', 'Mercedes Benz', 1.6)

...本身,而是通过直接读取和存储数据作为类对象?

我试过这样解析文件中的数据:

    cars = []
file = open('store-data.txt')
content = file.readlines()
for x in range(len(content)):
new_car = Car()
cars.append(new_car)

for car in cars:
print(car)

但是得到如下错误:

TypeError: __init__() missing 3 required positional arguments: 'model', 'name', and 'price'.

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com