In Python, every object is an instance of a class.
Knowing the class name of an object or instance is an essential piece of information, especially when working with large codebases.
To get the class name of an instance in Python, we can use the type()
function.
The type()
function returns the type of an object or instance, which is the class it belongs to.
Here’s an example of how to get the class name of an instance in Python:
class MyClass: pass my_instance = MyClass() print(type(my_instance).__name__)
In this example, we define a class called MyClass
.
We create an instance of the class called my_instance
and store it in a variable.
We then use the type()
function to get the type of my_instance
.
We use the __name__
attribute to get the name of the class, which is printed to the console.
When we run this program, we will see the output:
MyClass
This indicates that the class name of my_instance
is MyClass
.
In summary, to get the class name of an instance in Python, we can use the type()
function and the __name__
attribute to obtain the name of the class that the instance belongs to.