在 Python 中,是否可以从 Bar 自身中获取包含另一个对象 Bar 的对象,比如 Foo?这是我的意思的一个例子
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()
这可能吗?谢谢!
最佳答案
传递对 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.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()
关于python - 从 python 中获取容器/父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10791588/