【发布时间】:2018-02-25 00:50:24
【问题描述】:
在条件的所有可能分支中重新定义变量之前,是否可以防止出现问题?
例如应该这样的代码:
# 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 分配值,但我可以看到为什么从内务角度来看,知道变量被分配给某物是件好事。
例如 if 第一个示例中没有 except 语句,那么 textureIndices 不会总是被定义,return 会导致错误。
但是,如果不转发定义在条件的两个原因中定义的变量,会有问题吗?
【问题讨论】:
-
在第一种情况下,您使用
except而不是except SomeError。由于您不应该将所有错误都放在一起,因此在良好实践中,您的变量可能不存在,除非您之前定义它。 -
“应该重写”的出处是什么?编译器和运行时系统对此很好。
标签: python conditional-statements