简体   繁体   中英

Generating same numbers in array of Objects - Python

Ive got problem with generating same numbers in my code im not using any seed and evry, the object is created in the loop it has same numbers inside array.

class Car:
    genome = list()

    def __init__(self, genome = None):


        self.createGenome()
        print(self.genome)

    def createGenome(self):
        for x in range(genomeLength):
            #if len(self.genome) < 500:
            #    self.genome.append(random.randint(0, 6))
            number = randomNumber()
            self.genome.append(randomNumber())

class GenerationOfCars:
    count = 50
    generation = list()

    def __init__(self):
        self.createGeneration()
        #print(self.generation)

    def createGeneration(self):
        for x in range(self.count):
            car = Car()
            self.generation.append(car)
            print(x)
def randomNumber():
    return randint(1,10)
generation = GenerationOfCars()
singlePointCrossover(generation.generation[0], generation.generation[1])
print(generation.generation)

im trying to make 50 cars with unique random instructions but its still same for every car. But the objects created and appended into list are not the same.

Like @jasonharper already mentioned your problem is that genome is a class attribute. It is the same list for all of your cars. To make it worse, each car creation extends the list with genomeLength number of random values.

Move self.genome = self.createGenome() to the __init__() and it should be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM