Python中类的调用函数时参数的数量错误

时间:2013-09-02 05:02:23

标签: python syntax-error

我试图在python中编写遗传算法的实现。它说我只有一个允许的时候用两个参数调用它,但我确定不是。

以下是相关代码:

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

这是我从类初始化和调用时的代码:

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

从IDLE返回以下错误:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

类的方法会自动将类的实例作为第一个参数传递(按惯例命名为self):

def mutate(self, array):