打破循环依赖

时间:2014-11-07 13:47:23

标签: python python-2.6

a.py:

def factory_a(name):
    return "A"

def run():
    a = factory_a("A")
    from b import factory_b 
    friend_of_a = factory_b("B")
    print(a)
    print(friend_of_a)

b.py:

def factory_b(name):
    return "B"

def run():
    b = factory_b("B")
    from a import factory_a 
    friend_of_b = factory_a("A")
    print(b)
    print(friend_of_b)

如果导入已放置在每个模块的开头而不是run(),那么由于循环导入,这将无法工作。因此,我想知道我是否正确地解决了这个问题,就像我在下面所做的那样。你会怎么做呢?

1 个答案:

答案 0 :(得分:1)

代码有效......现在,我不喜欢它。这种相互依赖使得代码难以理解和扩展。这样的事情看起来好多了:

a.py

def factory_a(name):
    return "A"

b.py

def factory_b(name):
    return "B"

controller.py

from a import factory_a     
from b import factory_b     

def run_a():
    a = factory_a("A")        
    friend_of_a = factory_b("B")
    print(a)
    print(friend_of_a)

def run_b():
    b = factory_b("B")
    friend_of_b = factory_a("A")
    print(a)
    print(friend_of_b)