Wrong number of arguments when a calling function

2019-03-03 08:29发布

问题:

I'm trying to write an implementation of a genetic algorithm in python. It says there I am calling it with two arguments when only one is allowed, but I'm sure I'm not.

Here is the relevant code:

class GA:
    def __init__(self, best, pops=100, mchance=.07, ps=-1):
        import random as r

        self.pop = [[] for _ in range(pops)]

        if ps == -1:
            ps = len(best)

        for x in range(len(self.pop)): #Creates array of random characters
            for a in range(ps):
                self.pop[x].append(str(unichr(r.randint(65,122))))

    def mutate(array):
        if r.random() <=  mchance:
            if r.randint(0,1) == 0:
                self.pop[r.randint(0, pops)][r.randint(0, ps)] +=1
            else:
                self.pop[r.randint(0, pops)][r.randint(0, ps)] -=1

This is the code when I initialize and call from the class:

a = GA("Hello",10,5)
a.mutate(a.pop)

which returns the following error from IDLE:

TypeError: mutate() takes exactly 1 argument (2 given)

How can I fix this?

回答1:

Methods of a class are automatically passed the instance of the class as their first argument (it's named self by convention):

def mutate(self, array):