【发布时间】:2017-10-27 15:06:16
【问题描述】:
在 python 中使用 OOP 'State' 模式导致我遇到了这个依赖问题:StateA、StateB 和 StateC 是实现相同方法 event1 的 3 个状态。StateB从StateA 继承其行为。
文件 a.py:
#from b import StateB
from c import StateC
class StateA(object):
def event1(self):
return StateC()
print type(StateA().event1())
文件 b.py:
import a
class StateB(a.StateA):
def event1(self):
return self
文件 c.py:
class StateC(object):
def event1(self):
return self
只要我在a.py 中不需要StateB,就可以。但是如果我想在StateA 中使用StateB 类型呢?
导入StateB(参见a.py 中的第一行注释)会导致此循环依赖错误:
ImportError: cannot import name StateB
【问题讨论】:
-
您可以尝试进行本地导入(在某些特定方法中),而不是在文件顶部导入它。
-
如果更改文件 b 的全局导入会发生什么?
-
如果我在方法 StateA.event1() 中移动文件 b 上的全局导入,则会出现同样的错误
标签: python oop circular-dependency state-pattern