简体   繁体   English

Python:获取实例化类的名称?

[英]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 created the self.x instance? 如何派生创建self.x实例的类名? In other words, if I was given the instance self.x, how do I get the name 'Class1'? 换句话说,如果给我实例self.x,我怎么得到名称'Class1'? Using self.x.__class__.__name__ will obviously only give you the Class2 name. 使用self.x.__class__.__name__显然只会给你Class2的名字。 Is this even possible? 这甚至可能吗? Thanks. 谢谢。

You can't, unless you pass an instance of the 'creator' to the Class2() constructor. 除非将“creator”的实例传递给Class2()构造函数,否则不能。 eg 例如

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. __init__()方法中为相关类设置一个变量,稍后再检索该变量。

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. 无论如何,最好的方法是明确地将创建者传递给构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM