Python Program to Get the Class Name of an Instance

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:

  1. Class Definition:
  • A class named MyClass is defined using the class keyword. This class currently has no attributes or methods defined within it.
  1. Instance Creation:
  • An instance of the MyClass class 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.
  1. Getting Class Name:
  • The type() function is employed to retrieve the type of the object obj, which corresponds to its class.
  • type(obj) returns a type object representing the class of obj.
  1. Accessing Class Name Attribute:
  • The __name__ attribute of the type object returned by type(obj) is accessed.
  • This attribute contains the name of the class as a string.
  1. Storing Class Name:
  • The class name obtained from the __name__ attribute is stored in the variable class_name.
  1. Printing Class Name:
  • The class name stored in class_name is printed to the console using the print() function.
  1. Output:
  • Upon execution, the program outputs the class name of the instance obj to 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


Download

By Admin

Leave a Reply

Your email address will not be published. Required fields are marked *