它是否会阻止问题在重新定义条件的所有可能分支之前定义变量?在条件中声明变量是否存在问题?
例如应此代码:
# 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