我正在尝试将一些GA代码从Javascript转换为Python,但是我无法使代码正常工作。你能帮我解决这个问题吗?
代码如下:
from math import floor
from random import randrange
class DNA:
@staticmethod
def newChar():
c = floor(randrange(63,122))
if c == 63:
c = 32
if c == 64:
c = 46
return chr(c)
def __init__(self,num):
self.num = num
self.genes = list()
self.fitness = 0
for i in range(self.num):
self.genes.append(newChar())
def getPhrase(self):
return ''.join(self.genes)
def calcFitness(self,target):
score = 0
for i in range(len(self.genes)):
if self.genes[i] == target[i]:
score += 1
self.fitness = score / len(target)
myDna = DNA(10)
每当我运行此代码时,都会出现此错误:
NameError: name 'newChar' is not defined
答案 0 :(得分:0)
要在类中调用函数,请使用self.xxx
。因此,在您的情况下,请使用self.newChar()
而不是newChar()