I wrote this piece of code and I can’t figure out what I exactly did wrong. I create two instances of the ‘Route’ class, and somehow they share the value for the ‘coords’ list.
import random
class Route():
def __init__(self):
self.coords = []
self.distance = 0
def Generate(self, cities):
random.shuffle(cities)
self.coords = cities
class Citymap():
def __init__(self, nr):
self.Nr_of_cities = nr
self.cities = []
def Generate_map(self):
for i in range(0, self.Nr_of_cities):
self.cities.append((random.randint(0, 750), random.randint(0, 750)))
city = Citymap(6)
city.Generate_map()
a = Route()
a.Generate(city.cities)
b = Route()
b.Generate(city.cities)
print a.coords
print b.coords
The output of a and b:
[(429, 713), (336, 611), (555, 465), (397, 227), (222, 412), (491, 322)]
[(429, 713), (336, 611), (555, 465), (397, 227), (222, 412), (491, 322)]
a and b should be different instances but somehow they end up sharing the ‘coords’ variable. Could someone help me out?
You have to clone the
city.citieslist or it will just be shared between them :