我正在设计一个模拟图灵机的程序,将规则放在单独的文件中以方便编辑。不幸的是,它第一次尝试从ruleTable进行计算时会抛出NameError。

令人讨厌的代码段:

import TheRules

def turIt():
    global ruleTable #Global has been used here.
    tapeSegment = tape[tapePos]
    for x in range(0,len(ruleTable)): #Error here.
        if ruleTable[x][2] == machineState and ruleTable[x][3] == tape[tapePos]:
            machineState = ruleTable[x][4]
            tape[tapePos] = ruleTable[x][5]
            move(ruleTable[x][6])


规则:

ruleTable = [1]
ruleTable[0] = ("startRule","anyVal","anyVal","1","1",1)
#New rules go down here:


准确地说:“ NameError:未定义全局名称'ruleTable'”

解决这个问题的最简单方法是什么?我对此完全感到困惑。

最佳答案

import TheRules仅将TheRules模块加载到本地名称空间,而不加载其内容(变量,函数等)。
使用from TheRules import ruleTableruleTable加载到本地名称空间。
或使用TheRules.ruleTable访问变量

10-06 10:19