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.
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.
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.
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.
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 !" ))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With