2014-11-23 54 views
1

此代碼無誤地運行。但是在函數find_available_filenumber中,變量render_folder未被聲明。所以我的問題是爲什麼這不會產生錯誤?爲什麼我的一個變量不需要聲明而另一個呢?

如果我刪除full_filename作爲參數,我得到的錯誤:

UnboundLocalError: local variable 'full_filename' referenced before assignment. 

我不明白爲什麼這不也與render_folder發生,下面我的代碼示例:

import bpy 
import os 

#Functions 
def find_available_filenumber(full_filename): 
    file_number = 1 

    while os.path.exists(render_folder + "\\" + full_filename): 
     file_number += 1 
     full_filename = create_full_filename(filename, file_number) 

    return file_number 

def create_full_filename(filename, file_number): 
    file_extension = ".avi" 
    full_filename = filename + "_" + str(file_number) + file_extension  

    return full_filename 

#Paths and names 
project_folder = "F:\\06_MotionPath_Dev\\" 
os.chdir(project_folder) 

render_folder = "Render\\QuickRenderAddon" 
filename = bpy.context.scene.name #Returns "QuickRenderAddon" 
full_filename = create_full_filename(filename, 1) 
filepath = render_folder + "\\" + full_filename 

available_number = find_available_filenumber(full_filename) 
print("Avail nmb: " + str(available_number)) 

回答

3

啊,是經典的「分配之前引用的」

我寫了一些示例代碼,顯示是怎麼回事。

test = "toast!" 
toast = "test!" 

def func(): 
    print test 
    print toast 

func() 

上面的輸出是

toast! 
test! 

這表明,我們可以看到全局變量,但如何寫呢?我不想'敬酒'做'測試!'不再是,而是「麪包+烤麪包機!」。讓我們寫出來。

test = "toast!" 
toast = "test!" 

def func(): 
    print test 
    toast = "bread+toaster!" 
    print toast 

func() 
print toast 

此輸出

toast! 
bread+toaster! 
test! 

你會發現,我們能夠打印出本地分配的變量,但是全局變量並沒有改變。現在,我們來看另一個例子。

test = "toast!" 
toast = "test!" 

def func(): 
    print test 
    print toast 
    toast = "bread+toaster!" 
    print toast 

func() 
print toast 

這將引發錯誤

UnboundLocalError: local variable 'toast' referenced before assignment 

爲什麼?因爲你稍後將變量'toast'聲明爲局部變量。 Python注意到這一點並停止代碼以防止錯誤。稍後設置'toast'不會改變全局變量,而是在稱爲'toast'的函數內聲明局部變量。

你如何解決這個問題?

第一是增加你的函數中的全局條款

test = "toast!" 
toast = "test!" 

def func(): 
    global toast 
    print test 
    print toast 
    toast = "bread+toaster!" 
    print toast 

func() 
print toast 

此輸出

toast! 
test! 
bread+toaster! 
bread+toaster! 

您還可以修改您的代碼放到一個類結構,因爲這樣的。

class bread(): 
    def __init__(self): 
     self.test = "toast!" 
     self.toast = "test!" 

    def func(self): 
     print self.test 
     print self.toast 
     self.toast = "bread+toaster!" 
     print self.toast 

b = bread() 
b.func() 

在我看來,類是最好的解決方案,因爲它會增加模塊性,並幫助您減少意大利麪代碼。

1

編輯:忽略我,我在手機上,所以我沒有正確閱讀。

錯誤狀態「在賦值之前引用」。換句話說,在爲它寫入值之前,您正試圖從該變量中讀取一個值。

我有一種感覺,這個錯誤是因爲你有條件的原因,因爲你在寫入while循環體之前檢查這個值。

1

This code runs without errors. But in the function find_available_filenumber the variable render_folder isn't declared. So my question is why this doesn't produce an error?

這是因爲render_folder在時間find_available_filenumber被稱爲聲明,定義你的功能時,即使其未聲明。

相關問題