Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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.

like image 221
Chuck Avatar asked Oct 20 '09 10:10

Chuck


People also ask

How do I get the class name of an object in Python?

The first and easiest method to get a class name in python is by using __class__ property which basically refers to the class of the object we wish to retrieve. Here we combine the property with __name__ property to identify the class name of the object or instance.

What is instantiating a class Python?

Instantiating a class is creating a copy of the class which inherits all class variables and methods. Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines.

What is instantiating the class?

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

How do you create an instance of a class dynamically in Python?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object. print ( type ( "Geeks4Geeks !" ))


1 Answers

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

like image 164
workmad3 Avatar answered Sep 22 '22 21:09

workmad3