2012-05-28 40 views
18

在Python中,是否有可能从Bar内部获得包含另一个对象Bar的对象,如Foo?这里是我的意思在python中获取容器/父对象

class Foo(object): 
    def __init__(self): 
     self.bar = Bar() 
     self.text = "Hello World" 

class Bar(object): 
    def __init__(self): 
     self.newText = foo.text #This is what I want to do, 
           #access the properties of the container object 

foo = Foo() 

一个例子是这可能吗?谢谢!

+2

你有一个错字;在'Foo .__ init__'中,'self.bar = Foo()'应该是'self.bar = Bar()'。否则,你有一个无限循环(为了创建一个Foo,你首先必须创建一个Foo)。 –

+0

谢谢,修正! :) –

回答

29

传递一个参考吧对象,像这样:

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.text 

foo = Foo() 

编辑:由@thomleo指出,这可能会导致垃圾回收问题。建议的解决方案在http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/的布局,看起来像

import weakref 

class 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.text 

foo = Foo() 
+0

谢谢,这个作品。我能看到的唯一问题是,当我尝试访问很多对象时,我将调用“parent.parent.parent.etc”。有没有更好的方法来做到这一点? –

+3

如果我没有弄错,那还有一个主要问题。当你尝试做“del foo”时,它不一定会将其销毁,因为它仍然存在于它所包含的“Bar”的''.parent''属性中... –

+0

@MichaelMcClenaghan,在这种情况下,您可以迭代多次而不是手动拼写。当然,这取决于结构... – batbrat

4

是有可能得到的对象,说富,包含另一个对象,酒吧,从酒吧内本身?

不是“自动”,因为语言不是这样构建的,特别是,语言的构建使得无法保证Foo的存在。

也就是说,你总是可以明确地做到这一点。像Python中的其他标识符一样,属性只是名称,而不是数据的存储空间;因此没有任何东西阻止您让Bar实例具有手动分配的foo属性,该属性是Foo实例,反之亦然。

-3

怎么样使用继承:

class Bar(object): 
    def __init__(self): 
     self.newText = self.text 

class Foo(Bar): 
    def __init__(self): 
     self.txt = 'Hello World' 
     Bar.__init__(self) 

foo = Foo() 
print foo.newText