python oop import - NameError混淆

时间:2015-04-28 02:16:31

标签: python oop

我写了一些代码,试图通过从字符列表中随机选择来尝试接近目标字符串,但我有一些问题,我不太明白。

import random

class MonkiesGo:

    __chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

    def __init__(self, targetString):
        __targetString = targetString.lower()
        __targetList = list(targetString)
        __attemptList = []
        __unmatchedIndexes = [ x for x in range(0, (len(targetString)-1)) ]

    def attemptToSolve(self):

        if len(__unmatchedIndexes) == 0:
            __attemptString = ''.join(__attemptList)
            return __attemptString, __targetString
        else:
            for index in __unmatchedIndexes:
                __attemptList[index] = randomChar()

    def updateSolutionProgress(self):
        for indexCheck in __unmatchedIndexes:
            if __targetList[index] == __attemptList[index]:
                __indexToClear = __unmatchedIndexes.index(index)
                del __unmatchedIndexes[indextToClear]

    def __randomChar(self):
        return __chars[ random.randint(0,26) ]

当我将它导入终端的python shell时,按如下方式创建一个对象:

from monkies import MonkiesGo 
mk = MonkiesGo("hello")
mk.attemptToSolve()

我收到错误:

  

追踪(最近一次通话):     文件“”,第1行,在中     在attemptToSolve中输入第15行的“path / to / the / file / monkies.py”        if len(__ unmatched 0:NameError:name'_MonkiesGo__unmatched'未定义

造成这种情况的原因是什么,为什么在MonkiesGo之前有下划线?

提前谢谢。

更新至:

import random

class MonkiesGo:


    def __init__(self, targetString):
        self.targetString = targetString.lower()
        self.targetList = list(targetString)
        self.attemptList = []
        self.unmatchedIndexes = [ x for x in range(0, (len(targetString)-1)) ]
        self.chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

    def attemptToSolve(self):

        if len(self.unmatchedIndexes) == 0:
            self.attemptString = ''.join(self.attemptList)
            return self.attemptString, self.targetString
        else:
            for index in self.unmatchedIndexes:
                self.attemptList[index] = randomChar()

    def updateSolutionProgress(self):
        for indexCheck in self.unmatchedIndexes:
            if self.targetList[index] == self.attemptList[index]:
                indexToClear = self.unmatchedIndexes.index(index)
                del self.unmatchedIndexes[indextToClear]

    def randomChar(self):
        return self.chars[ random.randint(0,26) ]

现在我收到了关于randomChar的名称错误..?

1 个答案:

答案 0 :(得分:0)

您没有创建任何实例变量。在函数__init__中,诸如__targetString之类的变量是本地的,仅在函数内定义。当您调用函数attemptToSolve时,变量__unmatchedIndices也是本地的,因此未定义。双下划线不会自动生成实例变量;也许这就是你的困惑。

而不是__targetString = what,你应该使用self .__ targetString = what,或者更好的是删除下划线并仅使用self.targetString。这会创建一个成员变量。使用相同的self.targetString语法在成员函数中访问它。查看Python附带的教程。