python导入循环问题

模拟一个简单的场景

a.py中有一个函数a(),需要调用b.py中的函数b(), 而b.py中的函数c()又需要调用a(),这就出现了循环导入。代码如下所示:

from b import b
print '---------this is module a.py----------'
def a():
    print "hello, a"   
    b()

a()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
from a import a
print '----------this is module b.py----------'
def b():
    print "hello, b"

def c():
    a()

c()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行:python a.py,报错如下:

zy@zy:~/code/python/test/import$ python a.py
Traceback (most recent call last):
  File "a.py", line 1, in <module>
    from b import b
  File "/home/zy/code/python/test/import/b.py", line 1, in <module>
    from a import a
  File "/home/zy/code/python/test/import/a.py", line 1, in <module>
    from b import b
ImportError: cannot import name b
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在a.py中导入b.b(),在导入b文件的时候,又要去导入a文件,a文件又要去导入b文件,这是一个死循环了,自然是不允许的。

解决方法:

  • 可以将导入模块的语句放在局部(函数)里。如下所示:
print '---------this is module a.py----------'
def a():
    print "hello, a"
    from b import b 
    b()

a()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
rint '----------this is module b.py----------'
def b():
    print "hello, b"

def c():
    from a import a
    a()

c()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行:python a.py,结果如下:

zy@zy:~/code/python/test/import$ python a.py
---------this is module a.py----------
hello, a
----------this is module b.py----------
---------this is module a.py----------
hello, a
hello, b
hello, a
hello, b
hello, b
    原文作者:约瑟夫环问题
    原文地址: https://blog.csdn.net/daijiguo/article/details/78265275
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞