开发者

How to get Python Object Parent?

开发者 https://www.devze.com 2023-03-17 18:21 出处:网络
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.

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 fro开发者_Python百科m 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.


(I know this is an old question but since it's unanswered...)
You could try messing with the garbage collector. Was going to suggest looking at the module level objects but some quick code experimentation gave this: Try the gc.get_referrers(*objs) function.

import gc

class Foo(object):
    """contains Bar"""
    def __init__(self, val):
        self.val = val
        self.bar = None

class Bar(object):
    """wants to find its parents"""
    def __init__(self, something):
        self.spam = something

    def find_parents(self):
        return gc.get_referrers(self)

The results aren't straightforward so you'll have to apply your own logic for how determine which f is the one you're looking for. Notice the 'f': <__main__.Foo object at ...> below:

>>> f = Foo(4)
>>> b = Bar('ham')
>>> f.bar = b
>>> b.find_parents()
[{'bar': <__main__.Bar object at 0x7f3ec5540f90>, 'val': 4}, <frame object at 0x238c200>,
{'b': <__main__.Bar object at 0x7f3ec5540f90>,
    'Bar': <class '__main__.Bar'>,
    'f': <__main__.Foo object at 0x7f3ec5540f10>,    # <-- these might be
                                          # the droids you're looking for
    '__builtins__': <module '__builtin__' (built-in)>,
    '__package__': None, 'gc': <module 'gc' (built-in)>, '__name__': '__main__',
    'Foo': <class '__main__.Foo'>, '__doc__': None
}]

For bonus points, use gc.get_referents(*objs) on those to check if the same b is in their list.

Some notes/caveats:

  • I think you should just pass the parent Foo object to Bar, either in init or another method. That's what I would do, instead of my suggestion above.
  • This SO answer points out some issues the garbage collector has when linking both ways - you're not currently doing that but if you do, fyi.


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


well, I donno what exactly you are trying. but I have done something like this.

class Node(object):

    def __init__(self, name):
        self.parent = ''
        self.child = []
        self.name = name

    def setParent(self, parent):
        if isinstance(parent, tempNode):
            self.parent = parent.name
            parent.setChild(self.name)

    def setChild(self, child):
        self.child.append(child)

    def getParent(self):
        return self.parent

    def getChild(self):
        return self.child

and to make a parent you can say

n1 = Node('Father')
n2 = Node('Son')
n2.setParent('Father') # it will set n1 as parent and n2 as child at the same time.

Hope this will help you.


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.


If you want inheritable objects do it properly

class Test(object):
    def __init__(self):
        self.a = 1

class Bobcat(Test):
    def __init__(self):
        Test.__init__(self)
        self.b = 4 


Maybe something like this?

class Alpha:
def __init__(self):
    self.a = None

def start(self):
    self.get_a()
    self.print()
    self.SubBravo(self).multiply()
    self.print()
    self.SubAlpha(self).add_two()
    self.print()

def get_a(self):
    self.a = int(input("Enter an integer: >>> "))

def print(self):
    print("a: ", self.a)

class SubAlpha:
    def __init__(self, parent):
        self.parent = parent

    def add_two(self):
        print("hello add_two")
        self.parent.a += 2
        self.parent.print()
        self.add_five()

    def add_five(self):
        print("hello add_five")
        self.parent.a += 5

class SubBravo:
    def __init__(self, parent):
        self.parent = parent

    def multiply(self):
        print("hello multiply")
        self.parent.a *= 10


Alpha().start()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号