Python中的导入错误

1 投票
2 回答
685 浏览
提问于 2025-04-16 08:14

在file1.py文件中:

      def test1():
        print "hi"

在file2.py文件中:

      from file1 import test1

      def test2():
        print "hello"

      test1()
      test2()

输出结果:

      hi
      hello

现在在file1中,如果我引入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

有人能解释一下为什么会这样,以及如何让它正常工作吗?

2 个回答

4

这是一个循环导入的问题。你在 file1 中导入了 file2,然后在 file2 的最上面又导入了 file1。这就导致了一个问题:file1 需要先加载 file2,而 file2 又需要先加载 file1,这样就形成了一个死循环。

至于怎么解决这个问题,你能说说你想要实现什么吗?为什么不把这两个函数放在同一个模块里,然后一次性导入呢?

2

在你尝试访问这个名字的时候,它在模块里还不存在。

撰写回答