Site icon Student Projects Live

Python Program to Get the Class Name of an Instance

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:
  1. Instance Creation:
  1. Getting Class Name:
  1. Accessing Class Name Attribute:
  1. Storing Class Name:
  1. Printing Class Name:
  1. Output:

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

Exit mobile version