获取实例的类名? [英] Getting the class name of an instance?

查看:86
本文介绍了获取实例的类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从中创建该对象的实例的基类是派生该实例的类的基类,那么如何找到在Python中创建对象实例的类的名称?

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?

正在考虑检查模块可能对我有所帮助,但似乎并没有给我我想要的东西.除了解析__class__成员之外,我不确定如何获取此信息.

Was thinking maybe the inspect module might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the __class__ member, I'm not sure how to get at this information.

推荐答案

您是否尝试过 __name__属性?即type(x).__name__将为您提供类的名称,我想这就是您想要的.

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

如果您仍在使用Python 2,请注意,上述方法适用于新式类仅(在Python 3+中,所有类都是新式"类).您的代码可能使用一些旧式类.两者均可使用:

If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

x.__class__.__name__

这篇关于获取实例的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆