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)
是否有可能从Bar本身中获取包含另一个对象Bar的对象(例如Foo)?
不是“自动”的,因为该语言不是那样构建的,尤其是该语言的构建方式使得无法保证Foo存在。
也就是说,您始终可以明确地执行此操作。就像Python中的其他所有标识符一样,属性只是名称,而不是数据的存储空间。因此,没有什么可以阻止您让Bar实例具有一个手动分配的foo属性,该属性是Foo实例,反之亦然。