Python循环引用 [英] Python circular references
本文介绍了Python循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图在同一文件中有两个相互引用的类。进行此工作的最佳方法是什么:
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.
有办法解决吗?
编辑:
这些键用于SQLAlchemy映射,它们实际上是类变量(不是实例)。
those keys are used for SQLAlchemy mapping, to they realy are class variables (not instance).
推荐答案
此会做你想做的事:
class Foo(object):
pass
class Bar(object):
pass
Foo.other = Bar
Bar.other = Foo
不过,我宁愿完全避免这种设计。
I would prefer to avoid such design completely, though.
这篇关于Python循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文