'module' object has no attribute 'Thread'解决方法及模块加载顺序

时间:2023-03-09 17:49:33
'module' object has no attribute 'Thread'解决方法及模块加载顺序

源码片段:

class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter

执行时提示如下错误:

Traceback (most recent call last):

File "threading.py", line 2, in <module>

import threading

File "I:\MY_TEST\py\thread\threading.py", line 7, in <module>

class myThread(threading.Thread):

AttributeError: 'module' object has no attribute 'Thread'

1、检查是否为threading和Thread拼写错误,认真对比后确认无误;
2、判断是否为threading模块没有安装,查询发现python3.4自带就有此模块;
3、最后检查脚本的名称是threading.py,怀疑是与模块名称冲突,导致加载错误,将脚本名称改为thread_ing.py后执行,正确


由此引出两个问题:

1、命名问题:不管是变量还是脚本名称,都不要和python本身的模块、关键字等重合;

2、Python加载模块顺序问题:

加载模块搜索路径被存储在sys模块中的path变量中,我们使用sys.path输出:

'module' object has no attribute 'Thread'解决方法及模块加载顺序

第一个参数是‘’(空串),代表是当前目录,后续的目录分别为PYTHONPATH目录和标准库目录,所以得到加载模块的顺序为:

1)当前主目录

2)PYTHONPATH目录

3)标准库目录