2012-03-21 35 views
0

我寫了一個功能,我想從該函數返回一個變量,但我一直收到錯誤返回函數變量錯誤〜局部變量「用戶」分配〜之前引用的Python

局部變量「用戶分配之前引用

我的功能是:

def txtelm(): 

    # Updates date field to the current date 
    if textElement.name == "DATE": 
     textElement.text = strftime("%y %m %d") 

    if textElement.name == "CHECK": 
     textElement.text = "AB"   

    # First code block replaces the "Drawn" title block initials 
    if docauthor == "Mike" and textElement.name == "DRAWN": 
     textElement.text = "MM" 
     user = "mm" 
     #print user 

    elif docauthor == "Amy" and textElement.name == "DRAWN": 
     textElement.text = "AB" 
     user = "ab" 
     #print user 

    elif docauthor == "Ian" and textElement.name == "DRAWN": 
     textElement.text = "IB" 
     user = "ib" 

    elif docauthor == "Chris" and textElement.name == "DRAWN": 
     textElement.text = "CM" 
     user = "cm" 

    elif docauthor == "Cynthia" and textElement.name == "DRAWN": 
     textElement.text = "CC" 
     user = "cc" 

    return user 

再往下我的代碼,我調用該函數:

for textElement in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"): 
     txtelm() 
     user = txtelm() 
     if textElement.name == "PATH": 
     textElement.text = outloc + "\\" + sitename.replace(" ", "_") + "_" + trunc + strftime("%d%b%y") + "_" + user 

我設置了一些打印消息來打印'用戶',但它似乎沒有返回任何東西。在我創建函數之前,我已經有了代碼,在'for循環'之下進行了硬編碼,並且它的工作原理....所以我很難理解它爲什麼沒有返回任何值。

有什麼建議嗎?

+1

稍微容易閱讀文本格式:'textElement.text = os.path.join(outloc,「%s_%s%s_%s」%(sitename.replace(「」,「_」),trunc,strftime (「%d%b%y」),user))' – 2012-03-22 15:10:27

+0

謝謝你的建議傑森。 – Mike 2012-03-22 16:24:43

回答

0

我猜你的if/elif沒有一個是正確的。

+0

做一個最後的'else',在那裏引發一個'exception'。像這樣..'提高ValueError(docauthor,textElement.name)' – Doboy 2012-03-21 21:47:56

0

在嘗試返回它之前,用戶從未被聲明過。在()txtelm開始

def txtelm(): 
    user = "" 

用戶設置爲空字符串,然後測試,如果用戶不爲空

for textElement in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"): 
     txtelm() 
     user = txtelm() 
     if user == "": 
      #handle the error 
1

你的函數沒有參數,但使用的是可變的「TextElement的」。你需要這樣定義函數:

txtelm(textElement): 

,因此稱之爲:

user = txtelm(textElement) 

的TextElement的從循環代碼值將被傳遞給函數。

我不確定txtelm()的第一個調用是什麼 - 它似乎沒有做任何事情。

編輯:

我說得太快了 - 這裏有幾個問題。首先是上面的,然後是'user'的定義:因爲每個定義都在'if'之內,當它們沒有匹配時它就不會被聲明。添加:

user = "" 

到您的函數的頂部,以防止這種情況。

再次編輯:'docauthor'也似乎沒有被定義 - 也許它應該是函數的另一個參數?

+0

我其實已經測試過這個,我仍然得到相同的錯誤.... – Mike 2012-03-21 22:31:29

+0

啊,是的,那是因爲你的'返回'超出了範圍用戶聲明。根據另一個答案,將'user =「」'放在函數的頂部。 – jimw 2012-03-21 22:40:49

+0

Python沒有塊範圍。 – 2012-03-22 01:09:30

相關問題