以下程序可以成功运行:
class Simple(object):
def __init__(self, name):
self.name = name
def __add__(self, other):
c = Composite()
c._members.append(self)
c._members.append(other)
return c
def __repr__(self):
return "Simple('%s')" % self.name
class Composite(object):
def __init__(self):
self._members = []
def __add__(self, obj):
if isinstance(obj, Simple):
out = Composite()
out._members = [k for k in self._members] + [obj]
elif isinstance(obj, Composite):
out = Composite()
out._members = [k for k in self._members + obj._members]
else:
raise TypeError
return out
if __name__ == "__main__":
s1 = Simple('one')
s2 = Simple('two')
s3 = Simple('three')
c1 = s1 + s2
c2 = c1 + s3
print c1._members
print c2._members
# output:
# [Simple('one'), Simple('two')]
# [Simple('one'), Simple('two'), Simple('three')]
我想将 、 和 的定义保留Simple
在Composite
三个__main__
不同的文件中,但我不能这样做,因为我无法导入Simple
,composite.py
也无法Composite
导入simple.py
.
您将如何修改类定义以便可以保留单独的文件?
谢谢你。
PS。我已经阅读了几个与“前向声明”相关的答案,但找不到我的具体问题的答案。