Python:获取实例化类的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1593632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Get name of instantiating class?
提问by Chuck
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.
如何派生创建 self.x 实例的类名?换句话说,如果给我实例 self.x,我如何获得名称“Class1”?使用self.x.__class__.__name__
显然只会给你 Class2 名称。这甚至可能吗?谢谢。
采纳答案by workmad3
You can't, unless you pass an instance of the 'creator' to the Class2() constructor. e.g.
您不能,除非您将“创建者”的实例传递给 Class2() 构造函数。例如
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
这会为您创建类之间的反向链接
回答by Paul McMillan
Set a variable on the class in question in your __init__()
method that you then retrieve later on.
在您的__init__()
方法中为相关类设置一个变量,然后您可以稍后检索。
You'll get better answers if you ask better questions. This one is pretty unclear.
如果你提出更好的问题,你会得到更好的答案。这个很不清楚。