Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This question already has an answer here:

I'm working on this OOP program in Python

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()

In the genNewString(self) method it keeps telling me the instance variable targetSize is not defined! I tried putting self.targetSize in its place but then I get an error SimpleString instance has no attribute 'targetSize' even though it is assigned as an instance variable.

share|improve this question

marked as duplicate by Joran Beasley, oefe, Ahmed Siouani, beryllium, tohuwawohu Nov 15 '13 at 9:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 5 down vote accepted

All members in Python require the explicit 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
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.