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!
Yes, it's possible. Even without passing the container reference on object creation, i.e. if your object is a class attribute. Your object needs to implement the descriptor protocol (have a
__get__()
):Pass a reference to the Bar object, like so:
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
Not "automatically", because the language isn't built like that, and in particular, the language is built such that there is no way to guarantee that Foo exists.
That said, you can always do it explicitly. Attributes, like every other identifier in Python, are just names, not storage space for data; so nothing prevents you from letting the Bar instance have a manually assigned
foo
attribute that is a Foo instance, and vice-versa at the same time.What about using inheritance: