从 Python 中的类调用函数时参数数量错误 [英] Wrong number of arguments when a calling function from class in Python
本文介绍了从 Python 中的类调用函数时参数数量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用 python 编写遗传算法的实现.它说当只允许一个参数时,我用两个参数调用它,但我确定我不是.
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.
相关代码如下:
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)
从 IDLE 返回以下错误:
which returns the following error from IDLE:
TypeError: mutate() takes exactly 1 argument (2 given)
我该如何解决这个问题?
How can I fix this?
推荐答案
类的方法会自动传递类的实例作为它们的第一个参数(按照约定命名为 self
):>
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):
这篇关于从 Python 中的类调用函数时参数数量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文