Skip to main content
 首页 » 编程设计

python之在python中导入错误

2025年05月04日17cmt

在 file1.py 中:

      def test1(): 
        print "hi" 

在 file2.py 中:

      from file1 import test1 
 
      def test2(): 
        print "hello" 
 
      test1() 
      test2() 

输出:

      hi 
      hello 

现在在文件 1 中,如果我包含 test2,我会收到以下错误:

    from file2 import test2 
 
    def test1(): 
      print "hi" 
 
   Traceback (most recent call last): 
   File "file1.py", line 1, in ? 
   from file2 import test2 
   File "/root/pyt/file2.py", line 1, in ? 
   from file1 import test1 
   File "/root/pyt/file1.py", line 1, in ? 
   from file2 import test2 
  ImportError: cannot import name test2 

有人能解释一下为什么以及如何让它发挥作用吗?

请您参考如下方法:

这是一个循环导入问题。您正在从 file1 导入 file2,然后在 file2 的顶层再次导入 file1。这意味着除非您导入 2,否则 1 无法加载,除非您导入 `1.

,否则 2 无法加载。

至于如何让它工作,你能解释一下你想做什么吗?为什么不将这两个函数放在同一个模块中并一次性导入?