为什么我不能在同一个程序中两次初始化 Python 队列?

Why can't I initialize a Python queue twice in the same program?

当我的程序如下...

import queue
queue = queue.Queue()
queue = None
queue = queue.Queue()

...我的输出如下:

AttributeError: 'NoneType' 对象没有属性 'Queue'


但是当我的程序如下...

import queue
queue = queue.Queue()
queue = None

...没有抛出错误消息。


为什么会这样?我需要重新初始化队列。

当您导入模块 queue 时,您实际上创建了一个引用类型 module 的对象的变量 queue。 然后,当您创建名为 queue 的队列时,您 重新定义了 变量 queue 为类型 queue.Queue 的对象。 难怪在那之后为什么不能调用 queue.Queue()! QED.

查看详情:

>>> import queue
>>> type(queue)
<class 'module'>
>>> # Here you redefine the variable queue: the module queue won't be accessible after that
>>> queue = queue.Queue()
>>> type(queue)
<class 'queue.Queue'>
>>> queue
<queue.Queue object at ***>
>>> # Here I try to call Queue() on an object of type Queue...
>>> queue = queue.Queue()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Queue' object has no attribute 'Queue'
>>> queue = None
>>> # And here I try to call Queue() on an object of type None...
>>> queue = queue.Queue()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'Queue'