-3

我正在用 Python 开发这个 OOP 程序

class SimpleString():    
    popSize = 1000 #Should be even number
    displaySize = 5
    alphatbet = "abcdefghijklmnopqrstuvwxyz "
    def __init__(self):
        pop = numpy.empty(self.popSize, object)
        target = self.getTarget()
        targetSize = len(target)

    def genNewPop(self):
        for i in xrange(self.popSize):
            pop[i] = Item(self.genNewString())

    def genNewString(self):
        s = ""
        for i in xrange(targetSize):
            s += chr(random.randint(len(alphabet)))
        return s

def main():
    ss = SimpleString()
    ss.genNewPop()
main()

在 genNewString(self) 方法中,它一直告诉我实例变量 targetSize 没有定义!我尝试将 self.targetSize 放在它的位置,但随后出现错误 SimpleString instance has no attribute 'targetSize' 即使它被分配为实例变量。

4

1 回答 1

5

Python 中的所有成员都需要显式self.

def __init__(self):
    self.pop = numpy.empty(self.popSize, object)
    self.target = self.getTarget()
    self.targetSize = len(self.target)

def genNewString(self):
    s = ""
    for i in xrange(self.targetSize):
        s += chr(random.randint(len(self.alphabet)))
    return s
于 2013-11-14T19:27:30.990 回答