Alex Rivera | Logout

How to get Python Object Parent?

Asked 2011-07-04T19:53:09.173
9

So, I'm trying to get the object that a custom object is 'inside' of. Here's an example.

Assume that o is an object - it doesn't matter what kind, it can just store variables.

o = Object()
class Test():
    def __init__(self):
        self.parent = o ## This is where I fall off; I want to be able to access
                        ## the o object from within the Test object

o.test = Test()

So, how would I get o from inside of Test? I know I could write the Test function to pass it in with

o.test = Test(o)

but I'd rather do it from inside the class definition.

Edit
Report

2 Answers

6

you could do something like this:

class Object:
    def __setattr__(self, name, value):
        if isinstance(value, Test):
            value.set_parent(self)
        self.__dict__[name] = value

class Test:
    def set_parent(self, parent):
        self.parent = parent

o = Object()
o.test = Test()
assert o.test.parent is o
answered 2011-07-04T20:00:42.647
1

Are you talking about inheritance? It's not very clear what you mean, but if you just want to do this:

class Test():
  def __init__(self,o):
    self.parent = o
  def other_method(self):
    do_something_with(self.parent)

It works perfectly.

**ed: This is not at all how you should do inheritance, if you want to do that. However, the way you describe your problem I think you want to create a tree-like structure of objects, not have classes inherit properties from each other.

answered 2011-07-04T19:57:57.127

Your Answer