How add add class instances to a list

3842 views python
0

I'm trying to get a bit better in classes. I want to add multiple cars (with attributes like plate number and time (it is for a security cam)) to a list. I had it working actually, but now it suddenly doesn't and I have no idea what is going on.

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)

Main Program:

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)

This gives me just an empty list. The car variables all look like ['1', '09:01:53', '2-ABC-32\n']. I actually want to have a list with cars with attributes. I had it working a couple of hours ago, but then I wanted to add a second list and now it stopepd working :(. Also do I have to return the car_list, or is this not necessary?

Thanks

answered question

I would suspect the file parsing.

@StephenRauch, you'd be right in general, but I'm pretty sure it's the new instance in print(Cars().cars)

1 Answer

6

Cars().cars is accessing the attribute cars from a new instance of Cars. Cars() in the last line of your code has just been initialized, and no CarId objects have been added to the cars attribute of Cars(). Instead, lookup cars from the returned result of make_lists_cars:

print(car_list.cars)

posted this

Have an answer?

JD

Please login first before posting an answer.