2012-05-28 42 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