我偶然发现了一种情况,使我无法理解 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 不喜欢我在第一种情况下打印值的原因。