Python循环引用
尝试在同一个文件中拥有两个相互引用的类。实现此功能的最佳方法是什么:
class Foo(object):
other = Bar
class Bar(object):
other = Foo
if __name__ == '__main__':
print 'all ok'
?
问题似乎在于,由于该属性位于类上,因此它会在类本身被解析后立即执行。
有办法解决吗?
编辑:
这些键用于 SQLAlchemy 映射,因为它们实际上是类变量(而不是实例)。
trying to have two class that reference each others, in the same file. What would be the best way to have this working:
class Foo(object):
other = Bar
class Bar(object):
other = Foo
if __name__ == '__main__':
print 'all ok'
?
The problem seems to be that since the property is on the class, since it tries to executes as soon as the class itself is parsed.
Is there a way to solve that?
edit:
those keys are used for SQLAlchemy mapping, to they realy are class variables (not instance).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将满足您的要求:
不过,我宁愿完全避免这种设计。
This would do what you want:
I would prefer to avoid such design completely, though.
假设您确实希望 Foo.other 和 Bar.other 成为类属性,而不是实例属性,那么这是有效的(我测试过,只是为了确定):
如果这是您所追求的实例属性,那么 aaronasterling 的答案更合适。
Assuming that you really want
Foo.other
andBar.other
to be class properties, rather than instance properties, then this works (I tested, just to be sure) :If it's instance properties that you're after, then aaronasterling's answer is more appropriate.