python - 另一个 UnboundLocalError : local variable referenced before assignment Issue

标签 python python-2.7

我偶然发现了一种情况,它阻碍了我对 Python 变量范围的理解。

代码如下:

transaction_id = None


def parseFileContent(hostID,marketID, content, writeToDB=False):
    features = _buildObjects(StringIO.StringIO(content))

    for feature in features:
        featureID =  adapter.addFeature(feature.name,boris)
        print transaction_id #breaks here UnboundLocalError: local variable 'transaction_id' referenced before assignment

        transaction_id = adapter.addFeatureTransactionToQueue(featureID, result[0], result[1], Command.ADD, boris, trans_id = transaction_id)

如果我用

替换最后一行
       adapter.addFeatureTransactionToQueue(featureID, result[0], result[1], Command.ADD, boris, trans_id = transaction_id)

一切正常。我需要了解 python 不喜欢我在第一种情况下打印值的原因。

最佳答案

Python 编译器将一个名称标记为函数的局部名称​​如果您分配给它。您的最后一行分配给 transaction_id 因此它被视为本地名称,而不是全局名称。

您需要通过在函数内使用 global 关键字,明确地告诉编译器 transaction_id 是全局的:

def parseFileContent(hostID,marketID, content, writeToDB=False):
    global transaction_id

如果没有赋值,一个名字被认为是非本地的,你不需要标记它。

关于python - 另一个 UnboundLocalError : local variable referenced before assignment Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280452/

相关文章:

python - 当尝试读取文件名来创建自定义数据集时,改为读取矢量信息

python 2.7 : ImportError: DLL load failed: The specified module could not be found

python - 为什么我的元类函数没有被子类调用?

c++ - 如何在 Python + SWIG 中接收引用和指针参数?

python - 在 python 中使用 Selenium、PhantomJS 和 Tor

python - 什么是 python 中的 Response 对象?

python - 如何改进我的算法运行时间? cpoptimithe 不建议

python - Django - 导入错误 : No module named apps

python - 如何设置python中字符的二进制形式显示的字节数?

python - 如何使用变量设置 Discord 嵌入消息的图像?