上一篇文章為:→1.2.1import導(dǎo)入模塊
循環(huán)導(dǎo)入
1. 什么是循環(huán)導(dǎo)入
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()
運(yùn)行python a.py
day12_其他知識(shí)-01.png
2. 怎樣避免循環(huán)導(dǎo)入
- 程序設(shè)計(jì)上分層,降低耦合
- 導(dǎo)入語句放在后面需要導(dǎo)入時(shí)再導(dǎo)入,例如放在函數(shù)體內(nèi)導(dǎo)入
將 import 語句移到函數(shù)的內(nèi)部,只有在執(zhí)行到這個(gè)模塊時(shí),才會(huì)導(dǎo)入相關(guān)模塊。
比如 a.py修改為
print '---------this is module a.py----------'
def a():
from b import b
print("hello, a")
b()
a()
b.py修改為
print '----------this is module b.py----------'
def b():
print("hello, b")
def c():
from a import a
a()
c()