从 python 中获取容器/父对象 [英] Getting container/parent object from within python

查看:29
本文介绍了从 python 中获取容器/父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In Python, is it possible to get the object, say Foo, that contains another object, Bar, from within Bar itself? Here is an example of what I mean

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()

Is this possible? Thanks!

解决方案

Pass a reference to the Bar object, like so:

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()

Edit: as pointed out by @thomleo, this can cause problems with garbage collection. The suggested solution is laid out at http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ and looks like

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 中获取容器/父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆