python - 从 python 中获取容器/父对象

标签 python class object containers

在 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/

相关文章:

python - 获取分支名称我在 Pull Requests 上使用 GitHub Webhook 处理

python - 为什么我的 python 看不到 pysqlite?

python - 如何链接多个全息图中的轴?

javascript - 如何将字符串点符号转换为对象引用,而不是嵌套

python - Sklearn StandardScaler + ElasticNet 具有可解释系数

C++ 一个文件多个类

C++ OOP 库存和项目类

javascript - 在javascript中同一类的其他方法中获取数组

javascript - 我如何从javascript中的数组中删除嵌套对象或父对象

perl - 如何在perl中返回正确的对象属性?