在条件中声明变量有问题吗?

2024-10-03 15:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在条件变量的所有可能分支中重新定义变量之前,定义变量是否可以防止出现问题?你知道吗

例如,此代码应:

    # 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会导致错误。你知道吗

然而,如果一个人不向前定义在条件的两个原因中定义的变量,会有问题吗?你知道吗


Tags: 代码returnif定义is分支condition条件
2条回答

变量字典(localsglobals取决于作用域)在创建变量时会被修改。你知道吗

在一种情况下,您创建变量,然后修改它,不管分支是什么:1 creation+assign,1 assign(完全覆盖旧值)。你知道吗

在省略预先创建的情况下,只有1个creation+assign,因此从技术上讲,在分支之前声明它要比更快(少一次字典查找,少一次无用的赋值)

除了帮助pythonide完成分支中的变量名之外,我想说的是,前面的声明在这种情况下是无用的,甚至是很麻烦的,因为这两个分支都被覆盖了(可能是一个旧的编译语言编程反射)。它唯一感兴趣的情况是一组复杂的分支,您只在几个分支中设置变量。这里不是这样。你知道吗

一个原因是它创建了冗余代码。在本例中,这似乎不是很明显,但以一个示例为例,您有多个unique except语句捕获代码中的多个异常。想象一下,如果有人想重构你的代码或添加额外的语句。你知道吗

textureIndices = None

try :
    textureIndices = [thing for thing in func()]fail

except InvalidTextException:
    textureIndices = []
    #lines to handle specific exception
except ValueError:
     textureIndices = []
     #lines to handle specific exception
except OSError:
     textureIndices = []
     #lines to handle specific exception

return textureIndices

如果有多个变量以这种方式运行,您可以看到这种情况是如何迅速升级的。通过先声明基本情况,可以减少冗余。你知道吗

textureIndices = []

try :
    textureIndices = [thing for thing in func()]fail

except InvalidTextException:
    #lines to handle specific exception
except ValueError:
     #lines to handle specific exception
except OSError:
     #lines to handle specific exception

return textureIndices

相关问题 更多 >