-1

So, I have the following class:

class GeneticAlgorithm():
    def breed_population(self, agents, fitness=0.10, crossover_rate=0.50, mutation_rate=0.10, mutation_degree=0.10, mutate=True):
        pass


    def crossover(self, child, parent_one, parent_two, crossover_rate, mutation_rate, mutation_degree, mutate):
        pass

When I try to run it, I get this error message:

agents = GeneticAlgorithm.breed_population(agents)
TypeError: breed_population() missing 1 required positional argument: 'agents'

Meaning that, for some reason, self is being treated like an actual argument instead of just giving the class access to all functions within the class.

How do I fix this?

Sören
  • 1,803
  • 2
  • 16
  • 23
Grant Allan
  • 189
  • 1
  • 4
  • 10
  • 2
    `self` _is_ a normal argument. When you call `obj.method()`, python implicitly passes `obj` as the first argument of `method`. You could call that argument whatever you please. If you want your `breed_population()` to be a _class_ method, define it as such using the `@classmethod` decorator. Note that your class method gets the _class_ as the first argument, and the convention is to call this argument `cls`. – Pranav Hosangadi Apr 22 '22 at 20:16
  • When you define a method with (self), it should be treated like an "instance method" and should only be called through **an object instance**. Like `algorithm = GeneticAlgorithm(); result = algorithm.breed_population(agents)`. The way you are using is the pattern of class method, which will need the `@classmethod` decorator – Bao Huynh Lam Apr 22 '22 at 20:20

1 Answers1

1

The problem you are having is that you trying to call the method on the class without creating an object.

agents = GeneticAlgorithm.breed_population(agents)

Should be:

ga_obj = GeneticAlgorithm()
agents = ga_obj.breed_population(agents)
Cargo23
  • 3,064
  • 16
  • 25