它是否會阻止問題在重新定義條件的所有可能分支之前定義變量?在條件中聲明變量是否存在問題?
例如應此代碼:
# Condition could fail
try:
textureIndices = someExpression()
# textureIndices is defined here if it does
except:
textureIndices = []
return textureIndices
重新寫成這樣:
# textureIndices is defined early and then re-defined in the conditional
textureIndices = None
try:
textureIndices = someExpression()
except:
textureIndices = 66
return textureIndices
,或者因except
打開等問題,是否存在與textureIndices
這裏定義一個問題:
if condition:
textureIndices = someExpression()
else:
textureIndices = 66
return textureIndices
減少問題?
唯一的區別是在第二個版本textureIndices
是在條件之外定義的。
我不明白爲什麼它很重要,因爲textureIndices
不可能在條件中被賦予一個值,但我可以看到爲什麼從管家的角度來看,很高興知道該變量被分配給某些東西。
例如如果有第一個例子沒有except
語句,那麼textureIndices
並不總是被定義和return
會導致錯誤。
但是,如果不轉發在兩個條件的原因中定義的定義變量,是否存在問題?
在你的第一個案例中,除了SomeError外,你使用'except'而不是''。既然你不應該把所有的錯誤都包括在內,那麼在你的實踐中,你的變量是不可能存在的,除非你先前定義了它。 – roganjosh
「應重寫」的來源是什麼?編譯器和運行時系統很好。 – Prune