What method do I call to get the name of a class?
Asked
Active
Viewed 5.1k times
5 Answers
46
It's not a method, it's a field. The field is called __name__
. class.__name__
will give the name of the class as a string. object.__class__.__name__
will give the name of the class of an object.

clahey
- 4,795
- 3
- 27
- 20
-
3Better written as `type(object).__name__`. – Hans Ginzel Mar 17 '21 at 15:04
12
I agree with Mr.Shark, but if you have an instance of a class, you'll need to use its __class__
member:
>>> 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>
-
Thanks! This helped dynamically naming a new class created with `type` and multiple bases. (e.g.: `type('_'.join(x.__name__ for x in bases), bases, {})`) – Wesley Baugh Mar 13 '13 at 01:03
4
From Python 3.3 and onwards we can use __qualname__
field for both classes & functions.
It differs from __name__
field for nested objects like class defined in other class
>>> class A:
class B:
pass
>>> A.B.__name__
'B'
>>> A.B.__qualname__
'A.B'
which may be quite useful.
Further reading

Azat Ibrakov
- 9,998
- 9
- 38
- 50
1
In [8]: str('2'.__class__)
Out[8]: "<type 'str'>"
In [9]: str(len.__class__)
Out[9]: "<type 'builtin_function_or_method'>"
In [10]: str(4.6.__class__)
Out[10]: "<type 'float'>"
Or, as was pointed out before,
In [11]: 4.6.__class__.__name__
Out[11]: 'float'

Vlad the Impala
- 15,572
- 16
- 81
- 124
-
1I think your underscores got eaten by markdown. You meant: 4.6.4.6.__class__.__name__ – Joe Hildebrand Sep 16 '08 at 23:43