我偶然发现了一种可以关闭我对Pythons变量作用域的理解的情况。另一个UnboundLocalError:赋值之前引用的局部变量问题
下面是代码:
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不喜欢我在第一种情况下打印价值。
我不使用全局变量,我只是对这个范围现象感到困惑。我不得不做这个例子,尽可能简洁地提出我的问题。 – bioffe