-2

I am making this very simple genetic algorithm in python. I made a custom class which is going to be the "creatures" evolving. I made instances of the class, and when I tried to call a function of the class from one of the objects it gave me the "'int' object is not callable" error.

Here is all my code:

import random as random

class Creature:
    def __init__(self, value1, value2, value3, generation, index):
        self.value1 = value1
        self.value2 = value2
        self.value3 = value3
        self.generation = generation
        self.index = index

    def generation(self):
        test = self.value1 * self.value2 - self.value3
        if test >= 50:
            newGeneration.append(self)
            self.index = len(newGeneration)


creatures = []
newGeneration = []
for i in range(100):
    value1 = random.randint(5,10)
    value2 = random.randint(5,30)
    value3 = random.randint(30,50)
    creatures.append(Creature(value1, value2, value3, 1, i))


for i in range(len(creatures) - 1):
    creatures[i].generation()


for i in newGeneration:
    print(i.value1 * i.value2 - i.value3)

when run, it gives me this:

    line 29, in <module>
    creatures[i].generation()
TypeError: 'int' object is not callable

Thank you in advance

Lorvarz76
  • 3
  • 1

2 Answers2

0

You try to call the method generation but it's hidden with the attribut generation whici is an int.

I'd call the method generate

class Creature:
    def __init__(self, value1, value2, value3, generation, index):
        self.value1 = value1
        self.value2 = value2
        self.value3 = value3
        self.generation = generation
        self.index = index

    def generate(self):
        test = self.value1 * self.value2 - self.value3
        if test >= 50:
            newGeneration.append(self)
            self.index = len(newGeneration)
azro
  • 53,056
  • 7
  • 34
  • 70
-1

Try taking out the -1, the range function already takes the first number down to 0; so it gives you the error because you are trying to call creatures[-1], although I thought that had to work.

peki
  • 669
  • 7
  • 24
Pablo López
  • 278
  • 2
  • 8