1

在 file1.py 中:

      def test1():
        print "hi"

在文件 2.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

有人可以解释为什么以及如何使其工作吗?

4

2 回答 2

4

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

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

于 2010-12-08T12:44:06.527 回答
2

当您尝试访问它时,该名称在模块中不存在。

于 2010-12-08T12:45:16.090 回答