Python Program to Get the Class Name of an Instance Ad Sponsored

ⓘ Sponsored by

In Python, a class is a blueprint or a template that defines a set of attributes and methods that are common to all objects of that class.

Python Code :

The below Python program gets the class name of an instance:

# Define a class
class MyClass:

# Create an instance of the class
my_object = MyClass()

# Get the class name using the type() function
class_name = type(my_object).__name__

# Print the class name
print(f"The class name is {class_name}.")

In this program, we first define a simple class MyClass using the class keyword.

We then create an instance of the class by calling the class constructor and assigning the resulting object to the variable my_object.

To get the class name of the instance, we use the type() function, which returns the type of an object. We pass the my_object instance as an argument to the type() function and then use the name attribute to get the class name as a string.

Finally, we print the class name using an f-string. Note that if you have multiple instances of the same class, they will all have the same class name, so this program will return the same class name regardless of which instance you pass to the type() function. Ad Sponsored

ⓘ Sponsored by