问题描述
我想在课堂上好一点。 我想在列表中添加多个汽车(具有板号和时间(用于安全凸轮)等属性)。 我实际上有它工作,但现在它突然没有,我不知道发生了什么。
class CarID:
def __init__(self, camera, cartime, plate):
self.camera = camera
self.plate = plate
self.cartime = cartime
class Cars:
def __init__(self):
self.cars = []
def addCar(self, car):
self.cars.append(car)
主程序:
def make_lists_cars(data):
car_list = Cars()
with open(data, newline='') as f:
f = f.readlines()
for line in f[2:-2]:
car = line.split("\t")
camera = car[0]
cartime = car[1]
plate = car[2]
car_list.addCar(CarID(camera, cartime, plate))
return car_list
data = 'verkeer.txt'
car_list = make_lists_cars(data)
print(Cars().cars)
这给了我一个空列表。 汽车变量看起来都像['1','09:01:53','2-ABC-32 \\ n']。 我实际上想要一个包含属性的汽车列表。 几个小时前我有它工作,但后来我想添加第二个列表,现在它stopepd工作:(。我还要返回car_list,或者这不是必要的吗?
谢谢
1楼
Cars().cars
正在访问属性cars
从一个新实例Cars
。
刚刚初始化了代码最后一行中的Cars()
,并且没有CarId
对象添加到Cars()
的cars
属性中。
相反,从返回的make_lists_cars
结果中查找cars
:
print(car_list.cars)