循环导入

1. 什么是循环导入

a.py

from b import b 

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

a()

b.py

from a import a

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

def c():
    a() 
c()

运行python a.py

itcast:day02$ python a.py 
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    from b import b 
  File "/home/itcast/python/python/day02/b.py", line 2, in <module>
    from a import a
  File "/home/itcast/python/python/day02/a.py", line 2, in <module>
    from b import b 
ImportError: cannot import name b

2. 怎样避免循环导入

  1. 程序设计上分层,降低耦合
  2. 导入语句放在后面需要导入时再导入,例如放在函数体内导入

results matching ""

    No results matching ""