1
我在这里挖了一个洞。Python,圆形依赖关系和单身人士
我正在PyDev中开发一个Python/Kivy应用程序。
该应用程序运行的很多系统(约10),所以我把它们推到一个引擎来处理一切。
为了便于操作,我抢通孔(最差)单身
main.py
#main.py
from code import engine
class MyApp(App):
def build(self):
engine.GetInstance().Initialize()
if __name__ == '__main__':
MyApp().run()
engine.py
#engine.py
from code import system1
from code import system2
gEngineInstance = None
def GetInstance():
global gEngineInstance
if (gEngineInstance == None):
gEngineInstance = Engine()
return gEngineInstance
class Engine():
mSystem1 = None
mSystem2 = None
def Initialize(self):
self.mSystem1 = system1.System1()
self.mSystem2 = system2.System2()
# Omitted
Unfortunatley发动机,这导致一些讨厌循环依赖。
主要有创建引擎,并了解它,它运行引擎进口,它运行系统导入。 问题:系统导入然后导入引擎,循环引用。
system1.py
#system1.py
from code import engine
class System1():
def SomeMethod(self):
engine.GetInstance().mSystem2.DoThings()
你得到的图片。 我绕过这个,现在这个可怕的代码,所有的地方:
system1.py
#system1.py
class System1():
def SomeMethod(self):
from code import engine
engine.GetInstance().mSystem2.DoThings()
这种情况的发生,直到该线,这是很好的停止进口,但它看起来错误,eveyrthing感觉就像我做错事一样。我试图通过引擎作为每个系统构造函数的引用,但是这有点重构,我想知道是否有更体面的方式来解决这种单例/循环引用问题为将来。
这是一个有趣的想法。有些关于这些动态语言的东西很难与我一起工作,但有时,没有严格的类型是非常方便的工具。我会给这个镜头,谢谢! – MintyAnt 2013-03-05 05:40:14