Python循环引用

发布于 2024-09-10 17:24:01 字数 325 浏览 5 评论 0原文

尝试在同一个文件中拥有两个相互引用的类。实现此功能的最佳方法是什么:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小女人ら 2024-09-17 17:24:01

这将满足您的要求:

class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

不过,我宁愿完全避免这种设计。

This would do what you want:

class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

I would prefer to avoid such design completely, though.

顾忌 2024-09-17 17:24:01

假设您确实希望 Foo.other 和 Bar.other 成为类属性,而不是实例属性,那么这是有效的(我测试过,只是为了确定):

class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

如果这是您所追求的实例属性,那么 aaronasterling 的答案更合适。

Assuming that you really want Foo.other and Bar.other to be class properties, rather than instance properties, then this works (I tested, just to be sure) :

class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

If it's instance properties that you're after, then aaronasterling's answer is more appropriate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文