1
我打算在函数'In_queue'中调用两个全局变量('head'和'tail'),结果是成功调用'head'但不'tail'。错误是:调用全局变量时未解析的引用?
UnboundLocalError: local variable 'tail' referenced before assignment.
在另一个函数'Out_queue'中,两个变量都调用成功。
代码:
tail = NODE(VALUE())
head = NODE(VALUE())
def In_queue():
try:
node = Create_node(*(Get_value()))
except:
print("OVERFLOW: No room availible!\n")
exit(0)
if not head.nextprt or not tail.nextprt:
tail.nextprt = head.nextprt = node
else:
tail.nextprt = node
tail = node
return None
def Out_queue():
if head.nextprt == tail.nextprt:
if not head.nextprt:
print("UNDERFLOW: the queue is empty!\n")
exit(0)
else:
node = head.nextprt
head.nextprt = tail.nextprt = None
return node.value
else:
node = head.nextprt
head.nextprt = node.nextprt
return node.value
您分配给tail,使其成为本地:'tail = node'。 UnboundLocalError有大量问题,我建议进行一些更多的研究。 – jonrsharpe
如果您分配给一个变量,它变成本地。如果你想分配给全局尾部变量,你需要在函数内部放置'global tail'。 – pschill