0

I have a program that has a Truck class and a Route class among other things. I am new to Python but my understanding is that when I call the "constructor" for a class, the instance of that class is not linked to any other instances of said class.

My Truck class has a local list variable in it. When I create multiple instances of this class and modify this list variable in only one of those instances, the list variable changes in all of the instances. The same is occurring with my Route class which has a similar local variable.

My Truck class code is as follows:

class Truck:

    def __init__(self, iD=-1, capacity=-1, speed=None, packageIDs=[], status="N/A", truckRoute=Route()):
        self.ID = iD
        self.capacity = capacity
        self.speed = speed
        self.packageIDs = packageIDs
        self.status = status
        self.truckRoute = truckRoute
        self.timeAlongRoute = time(8, 0)

My Route class code is as follows:

class Route:

    def __init__(self, routeIDList=[], departureTime=time()):
        self.routeIDList = routeIDList
        self.departureTime = departureTime
        self.returnTime = time()

An example of my issue in the main file:


    testRoute = Route()
    testRouteTwo = Route()

    testRoute.routeIDList.append(4)
    print("Route 1 contains: ", testRoute.routeIDList)
    print("Route 2 contains: ", testRouteTwo.routeIDList)

    testTruck = Truck(iD=1, capacity=16, speed=18)
    testTruckTwo = Truck(iD=2, capacity=16, speed=18)

    testTruck.addPackage(3)
    testTruck.ID = 45
    testTruck.printPackageList()
    testTruckTwo.printPackageList()

Results:

Route 1 contains:  [4]
Route 2 contains:  [4]
Truck 45 contains:
    Package ID:  3
Truck 2 contains:
    Package ID:  3

Any input or advice would be much appreciated. I don't doubt I'm likely missing something simple and/or fundamental.

martineau
  • 112,593
  • 23
  • 157
  • 280

0 Answers0