To display the name of an object in Python, you can use the __name__ attribute. Here's an example:
main.py90 chars7 linesIn this example, we create a class MyClass and create an instance of it called obj. We then print the name of the class using the __name__ attribute accessed through the obj.__class__ object.
Alternatively, if you want the name of the object itself, rather than its class, you can use the vars() function to retrieve the object's variables and their values, and then search for the variable that points to the object. Here's an example:
main.py114 chars5 lines
In this example, we create an instance of MyClass called my_var, and then use the locals() function to get a dictionary of local variables and their values. We then search through this dictionary for the variable that points to my_var by checking if its value is the same as my_var, and finally print the variable name using list comprehension.
gistlibby LogSnag