2016-01-26 24 views
0

朋友和我正在创建一个基本的概念证明反编译器,它接收一串十六进制值并返回一个更易读的版本。我们的代码如下在基本解压缩程序中引用“在赋值之前引用”的Python“本地变量”pc“

testProgram = "00 00 FF 55 47 00" 
# should look like this 
# NOP 
# NOP 
# MOV 55 47 
# NOP 

pc = 0 
output = "" 

def byte(int): 
    return testProgram[3 * int:3 * int + 2] 

def interpret(): 

    currentByte = byte(pc) 

    if currentByte == "00": 
     pc += 1 
     return "NOP" 

    if currentByte == "FF": 
     returner = "MOV " + byte(pc + 1) + " " + byte(pc + 2) 
     pc += 3 
     return returner 

while(byte(pc) != ""): 
    output += interpret() + "\n" 

print(output) 

上市然而,运行代码告诉我们这个

Traceback (most recent call last): 
    File "BasicTest.py", line 62, in <module> 
    output += interpret() + "\n" 
    File "BasicTest.py", line 50, in interpret 
    currentByte = byte(pc) 
UnboundLocalError: local variable 'pc' referenced before assignment 

因为PC是一个全局变量,应该不会是从任何地方使用吗?任何和所有的帮助表示感谢 - 如果你发现其他错误,随时留下评论指出他们!

回答

4

最近看到这个很多。当你做

if currentByte == "00": 
    pc += 1 # <---------- 
    return "NOP" 

你分配给本地变量pc,但pc未在本地范围内声明呢。如果您要修改全球pc,则需要明确声明该功能位于功能顶部

global pc 
相关问题