传递对Bar对象的引用,如下所示:
class Foo(object): def __init__(self): self.text = "Hello World" # has to be created first, so Bar.__init__ can reference it self.bar = Bar(self)class Bar(object): def __init__(self, parent): self.parent = parent self.newText = parent.textfoo = Foo()
编辑:
正如@thomleo指出的那样,这可能导致垃圾回收问题。建议的解决方案位于http://eli.thegreenplace.net/2009/06/12/safely-
using-destructors-in-python/中,看起来像
import weakrefclass Foo(object): def __init__(self): self.text = "Hello World" self.bar = Bar(self)class Bar(object): def __init__(self, parent): self.parent = weakref.ref(parent) # <= garbage-collector safe! self.newText = parent.textfoo = Foo()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)