深度阅读

How to get the class name of an object in Python

作者
作者
2023年08月22日
更新时间
8.26 分钟
阅读时间
0
阅读量

To get the class name of an object in Python, you can use the type() function or the .__class__.__name__ attribute. Here’s an example using type():

class MyClass:
    pass

obj = MyClass()
class_name = type(obj).__name__
print(class_name)

In this example, we create a new class MyClass, and then create an object obj of that class. Then, we use the type() function to get the type of the object, and access the __name__ attribute to get the name of the class as a string. The resulting class name is then printed to the console.

Alternatively, you can also use the .__class__.__name__ attribute to get the name of the class as a string directly from the object, like this:

class_name = obj.__class__.__name__
print(class_name)

This will give the same result as the previous example.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。