Python 中类的前向声明
以下程序可以成功运行:
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
中。
您将如何修改类定义以便可以保留单独的文件?
谢谢。
附言。我已经阅读了几个与“前向声明”相关的答案,但找不到我的具体问题的答案。
The following program can run successfully:
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')]
I would like to keep the definition of Simple
, Composite
, and __main__
in three different files, but I cannot do it because I cannot import Simple
into composite.py
and I cannot import Composite
into simple.py
.
How would you modify the class definition such that you can keep separate files?
Thank you.
PS. I've read several answers related to "forward declaration" but could not find an answer to my specific problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于在调用方法之前不需要任何引用,因此循环导入可以在这里工作。诀窍是使用完全限定的引用。
Since none of the references are needed until the methods are called, circular imports can work here. The trick is to use fully-qualified references.
问题是你得到了循环导入,对吧?
import Simple 在
__add__
方法中而不是在文件顶部,以避免循环依赖。它会稍微减慢 __add__ 方法的速度,但通常不会很明显。The problem is that you get circular imports, right?
import Simple in the
__add__
method instead of at the top of the file to avoid circular dependency. It will slow down the__add__
method somewhat, but usually not significantly.