2016-01-26 21 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 
相關問題