views:

2643

answers:

3

Example:

class Class1:
    def __init__(self):
        self.x = Class2('Woo!')

class Class2:
    def __init__(self, word):
        print word

meow = Class1()

How do I derive the class name that created the self.x instance? In other words, if I was given the instance self.x, how do I get the name 'Class1'? Using self.x.__class__.__name__ will obviously only give you the Class2 name. Is this even possible? Thanks.

A: 

Set a variable on the class in question in your __init__() method that you then retrieve later on.

You'll get better answers if you ask better questions. This one is pretty unclear.

Paul McMillan
+2  A: 

You can't, unless you pass an instance of the 'creator' to the Class2() constructor. e.g.

class Class1(object):
    def __init__(self, *args, **kw):
        self.x = Class2("Woo!", self)

class Class2(object):
    def __init__(self, word, creator, *args, **kw):
        self._creator = creator
        print word

This creates an inverse link between the classes for you

workmad3
Yeah I had a feeling this was the case, either that or setting an attribute. Thanks, this is the answer I was looking for.
Chuck
A: 

Your question is very similar to answered here. Note, that you can determine who created the instance in its constructor, but not afterwards. Anyway, the best way is to pass creator into constructor explicitly.

Denis Otkidach
Thanks, that helps. Yeah was just wondering if I was missing any other way to do it; other than passing it on in some form.
Chuck