从python中获取容器/父对象

Mic*_*han 28 python containers class object

在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()
Run Code Online (Sandbox Code Playgroud)

这可能吗?谢谢!

Hug*_*ell 44

传递对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()
Run Code Online (Sandbox Code Playgroud)

编辑:正如@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()
Run Code Online (Sandbox Code Playgroud)

  • 如果我没有弄错的话,那也存在一个重大问题.当你试图做``del foo``它不一定会破坏它,因为它的引用仍然存在于它包含的``Bar``的``.parent``属性中... (5认同)
  • 您不需要调用弱参考对象吗?self.newText = self.parent()。text (2认同)

Kar*_*tel 5

是否有可能从Bar本身中获取包含另一个对象Bar的对象(例如Foo)?

不是“自动”的,因为该语言不是那样构建的,尤其是该语言的构建方式使得无法保证Foo存在。

也就是说,您始终可以明确地执行此操作。就像Python中的其他所有标识符一样,属性只是名称,而不是数据的存储空间。因此,没有什么可以阻止您让Bar实例具有一个手动分配的foo属性,该属性是Foo实例,反之亦然。