繁体   English   中英

Python 中的“很可能是由于循环导入”

[英]"Most likely due to circular import" in Python

import threading
import time

start = time.perf_counter()

def do_something():
    print("Sleeping in 1 second")
    time.sleep(1)
    print("Done sleeping")

t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)

finish = time.perf_counter()
print(f"Finished in {round(finish-start,1)} seconds(s) ")

有谁知道为什么这段代码在运行时会返回此错误以及如何解决?

Traceback (most recent call last):
  File "c:/Users/amanm/Desktop/Python/Python Crash Course/threading.py", line 1, in <module>
    import threading
  File "c:\Users\amanm\Desktop\Python\Python Crash Course\threading.py", line 12, in <module>
    t1 = threading.Thread(target=do_something)
AttributeError: partially initialized module 'threading' has no attribute 'Thread' (most likely due to a circular import) 

当我在正常 IDLE 中运行此代码时,它似乎可以工作,但在 Visual Studio Code 中不起作用。

您创建的程序文件似乎名为threading.py ,并且您正在导入名为threading的库。 这会导致命名空间中的混乱。 请重命名您的程序(例如threading-example.py )。

导入模块时,python 首先检查当前工作目录中的文件,然后再检查其他内置模块。 因此,您可能有一个名为 threading.py 的文件,它没有必要的属性。 换句话说,您进行了循环导入。

我解决了我的问题,示例代码:

主.py

if __name__ == "__main__":
    import package2
    pack2class = package2.Package2(main=self)

包2.py

import Main
class Package2(object):
    def __init__(self, main:Main.MainClass): # for suggestion code
        pass # your codes ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM