The provided Python code demonstrates a straightforward method to retrieve the class name of an instance. Initially, a class named MyClass is defined. Following this, an object obj is instantiated from this class. To ascertain the class name of the instance, the program utilizes the type() function, which returns the type of an object. Specifically, it retrieves the class of the object obj using type(obj), and subsequently accesses the __name__ attribute of the returned type object to obtain the class name. Finally, the class name is printed to the console. This program can be easily adapted to any class by replacing MyClass with the desired class name and obj with the instance whose class name is to be retrieved.
Source code
class MyClass:
pass
# Create an instance of MyClass
obj = MyClass()
# Get the class name of the instance
class_name = type(obj).__name__
print("Class name of the instance:", class_name)
Description
Sure, here’s a step-by-step description of the provided Python code:
- Class Definition:
- A class named
MyClassis defined using theclasskeyword. This class currently has no attributes or methods defined within it.
- Instance Creation:
- An instance of the
MyClassclass is created by calling the class name followed by parentheses, resulting in the instantiation of an object. - This instance is assigned to the variable
obj.
- Getting Class Name:
- The
type()function is employed to retrieve the type of the objectobj, which corresponds to its class. type(obj)returns a type object representing the class ofobj.
- Accessing Class Name Attribute:
- The
__name__attribute of the type object returned bytype(obj)is accessed. - This attribute contains the name of the class as a string.
- Storing Class Name:
- The class name obtained from the
__name__attribute is stored in the variableclass_name.
- Printing Class Name:
- The class name stored in
class_nameis printed to the console using theprint()function.
- Output:
- Upon execution, the program outputs the class name of the instance
objto the console.
This program allows for the dynamic retrieval of the class name of any given instance, providing flexibility in handling objects of different classes within Python.
Screenshot

