I have 2 classes: Vehicle & Car.
Vehicle Class has a dictionary of Car objects & a heap.
ClassV.py:
from ClassC import Car
import heapq
class Vehicle:
MapOfCars_ID = {}
heap = [] # Stores the load factor of each car
counter = 0
def createCar(number, idnum):
C = Car(number, idnum) # Create a car object
self.MapOfCars_ID[counter] = C # Dict of Car_ID : Car Object
self.heapq.heappush(heap, (0.0, counter)) # Heap stores load factor, Car_ID
counter += 1
def AssignCar():
t = heapq.heappop(heap)
MapOfCars_ID[t[1]].addPassenger()
ClassC.py is the logic for creating a Car:
from ClassV import Vehicle
class Car:
size = 0;
occupiedSeats = 0
carId = -1
def __init__(size, id_number):
self.size = size
self.carId = id_number
print "Created Car with size " + self.size + " and ID number "+ self.carId
def addPassenger():
if self.occupiedSeats < self.size:
self.occupiedSeats += 1
# Code below adjusts the load factor of the car in the heap when a passenger is added to the car
# Load factor = seat-occupied/total-seats-in-the-car
for index, value in Vehicle.heap:
if value[1] == self.carId:
Vehicle.heap[index] = heap[-1]
heap.pop()
t = (float(self.occupiedSeats/self.size), self.carId)
heap.append(t)
heapq.heapify(Vehicle.heap)
break
else:
print "Car is full!"
The program is run from another file, main.py:
from ClassV import Vehicle
from random import randint
def main():
for i in range(1, 10): # Create 10 cars
r = randint(1,6) # Maximum number of seats could be 6 in a car
Vehicle.createCar(r, i) # <Car size, ID>
Vehicle.AssignCar()
if __name__ == "__main__":
main()
The intention of this program is to create 10 cars and then assign passengers to the car having minimal occupancy.
As shall be evident from the program, The heap
which is a class attribute of the class Vehicle is being updated in Car Class. And, Class Vehicle is creating an array of Car objects.
This gives me an error:
File "/home/Testing/ClassC.py", line 1, in <module>
from ClassV import Vehicle
ImportError: cannot import name Vehicle
I have searched around but could really find a resolution to this problem. What is the right way to resolve this problem?
Update: I got a few comments which explain that this is possibly a problem of circular imports and has 2 solution:
- Refactor the program to avoid circular imports
- Move the imports to the end of the module
I am looking for feedback as to how do I do either of these.