如何获取类名的字符串?

54

我应该调用哪个方法来获取一个类的名称?

5个回答

68
In [1]: class Test:
   ...:     pass
   ...: 

In [2]: Test.__name__
Out[2]: 'Test'

46

这不是一个方法,而是一个字段。该字段称为__name__class.__name__会以字符串的形式给出类的名称。 object.__class__.__name__会给出对象所属类的名称。


3
最好写成 type(object).__name__ - Hans Ginzel

13

我同意Shark先生的观点,但如果您有一个类的实例,您需要使用它的__class__成员:

>>> class test():
...     pass
...
>>> a_test = test()
>>>
>>> a_test.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute '__name__'
>>>
>>> a_test.__class__
<class __main__.test at 0x009EEDE0>

谢谢!这有助于动态命名使用type创建的新类和多个基类。 (例如:type('_'.join(x.__name__ for x in bases), bases, {})) - Wesley Baugh

4

1

在[8]中:str('2'.__class__)
输出[8]: "<type 'str'>"

在[9]中:str(len.__class__)
输出[9]: "<type 'builtin_function_or_method'>"

在[10]中:str(4.6.__class__)
输出[10]: "<type 'float'>"

或者,如之前所指出的那样,

在[11]中:4.6.__class__.__name__
输出[11]: 'float'


1
我认为你的下划线被Markdown吃掉了。你的意思是:4.6.4.6.__class__.__name__ - Joe Hildebrand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接