开发者

Python circular references

trying开发者_JAVA百科 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).


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜