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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:39:35  来源:igfitidea点击:

Python: Get name of instantiating class?

pythonclassinstance

提问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.

如果你提出更好的问题,你会得到更好的答案。这个很不清楚。

回答by Denis Otkidach

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.

您的问题与此处的回答非常相似。请注意,您可以确定谁在其构造函数中创建了实例,但不能在之后确定。无论如何,最好的方法是将创建者显式传递给构造函数。