Python: Get name of instantiating class?
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 c开发者_Go百科reated 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.
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
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.
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.
精彩评论